php – PDO用外键创建一个表

我在创建一个带有外键元素的
MySQL(PDO)的表时遇到困难,没有表创建的外键,但没有我收到此消息:

SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;

我试图寻找解决方案并调整代码,但似乎不断遇到这个问题.有没有解决方法,或者我是一个沃利?

<?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;
?> 

最佳答案 列的定义中的PRIMARY KEY是读取PRIMARY KEY(`column_name`)的单独定义的简写

FOREIGN KEY没有这样的速记.

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

请注意,您忽略了引用表的列名,您也应该也有ON DELETE和ON UPDATE参数.

点赞