2014-12-04 113 views
4

我有一個外鍵元素難度創建與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; 
?> 
+0

我可以問,你爲什麼要用PHP代碼創建你的表?在您的項目中訪問它之前,使用數據庫查看器創建它是否更實際? – silkfire 2014-12-04 13:17:11

+0

@silkfire儘管在這種情況下我同意你的觀點,但如果處理更復雜的應用程序可能會涉及到「創建臨時表」;) – 2014-12-04 13:21:34

+0

@NiettheDarkAbsol絕對如此,對於臨時表來說,它肯定是有意義的,但對於可重複使用的表格 - 出於開發者的觀點 - 我會發現在GUI中設計和構建表格更容易:) – silkfire 2014-12-04 13:24:28

回答

2

PRIMARY KEY在列的定義爲單獨定義讀取PRIMARY KEY (`column_name`)

FOREIGN KEY沒有這樣的速記簡寫。

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

請注意,您在引用表忽略了列名,你應該也有ON DELETEON UPDATE參數太多。

+0

謝謝Niet the Dark Absol,我試過了,現在又發現了另一個錯誤。我是一個新手開發人員,所以有耐心:-)這次的錯誤是:SQLSTATE [HY000]:一般錯誤:1215無法添加外鍵約束 – Gareth 2014-12-04 13:58:02

+0

嗨,也許這不可能是問題,但仍然提及,你要去的列添加爲外鍵必須被索引。 – 2018-02-08 19:04:01