PDO使用外键创建表

时间:2014-12-04 13:08:11

标签: php mysql-error-1064

我在使用带有外键元素的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;
?> 

1 个答案:

答案 0 :(得分:2)

列的定义中的

PRIMARY KEY是读取PRIMARY KEY (`column_name`)单独定义的简写

FOREIGN KEY没有这样的简写。

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

请注意,您忽略了引用表的列名,您也可能也有ON DELETEON UPDATE参数。