PDO creates a table with a foreign key

It is difficult for me to create a table with MySQL (PDO) with a foreign key element, without a foreign key the table creates a penalty, but without this message I get the following message:

SQLSTATE [42000]: syntax error or access violation: 1064 You have an error in the SQL syntax;

I tried to find a solution and adapt the code, but it seemed to be dealing with this all the time. Is there a fix, or am I wally?

<?php
$servername = "localhost";
$username = "root";
$password = NULL;
$dbname = "testapplciants";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


    //sql to create the activity registered table
    $sql = "CREATE TABLE Activity_Register (
    Activity_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    participant_id INT(6) FOREIGN KEY (participant_id) REFERENCES participants,
    entry_number INT(2),
    recorded_result INT(6),
    entry_date TIMESTAMP

    )";

    // use exec() because no results are returned
    $conn->exec($sql);
    echo "Table Activity Recorder created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?> 
+4
source share
1 answer

PRIMARY KEY in a column definition is an abbreviation for a separate definition that reads PRIMARY KEY (`column_name`)

FOREIGN KEY does not have such a shorthand.

`participant_id` INT(6),
FOREIGN KEY (`participant_id`) REFERENCES `participants` (`id???`)

, , , ON DELETE ON UPDATE.

+2

All Articles