我有一個外鍵元素難度創建與MySQL(PDO)的表,沒有外鍵的表中創建罰款,但沒有我得到這個消息: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;
?>
我可以問,你爲什麼要用PHP代碼創建你的表?在您的項目中訪問它之前,使用數據庫查看器創建它是否更實際? – silkfire 2014-12-04 13:17:11
@silkfire儘管在這種情況下我同意你的觀點,但如果處理更復雜的應用程序可能會涉及到「創建臨時表」;) – 2014-12-04 13:21:34
@NiettheDarkAbsol絕對如此,對於臨時表來說,它肯定是有意義的,但對於可重複使用的表格 - 出於開發者的觀點 - 我會發現在GUI中設計和構建表格更容易:) – silkfire 2014-12-04 13:24:28