2015-03-30 98 views
0

我知道這個問題來了好幾次,但我找不到我的代碼中的錯誤。在我的更新分支每$ stmt-> bindValue(...)返回TRUE,但我趕PDO例外PHP PDO更新:SQLSTATE [HY093]:無效的參數編號:參數未定義

SQLSTATE [HY093]:無效的參數號:沒有定義的參數

插入新條目可以正常工作。

在我的MySQL數據庫表「系統」的結構是:

id -> int(11), primary key 
computer_name -> varchar(255) 
cpu_speed -> int(11) 
ram_size -> int(11) 
mac_address -> varchar(255) 
operating_system -> varchar(255) 

我的錯誤拋出代碼:

// Search for mac_address. 
// If an entry with the same MAC exists update the entry. 
// Else, create a new entry 
$stmt = $pdo->prepare("SELECT * FROM system WHERE mac_address=:mac"); 
$stmt->bindValue(":mac", $mac_address, PDO::PARAM_STR); 
$stmt->execute(); 
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); 

// If no rows are returned, no entry exists => create a new one 
if(empty($rows)) 
{ 
    // Prepare statement 
    $stmt = $pdo->prepare("INSERT INTO 
     system(`computer_name`,`cpu_speed`,`ram_size`,`mac_address`, `operating_system`) 
     VALUES(:computer_name, :cpu_speed, :ram_size, :mac_address, :operating_system)"); 
    $stmt->bindValue(":computer_name", $computer_name, PDO::PARAM_STR); 
    $stmt->bindValue(":cpu_speed", $cpu_speed, PDO::PARAM_INT); 
    $stmt->bindValue(":ram_size", $ram_size, PDO::PARAM_INT); 
    $stmt->bindValue(":mac_address", $mac_address, PDO::PARAM_STR); 
    $stmt->bindValue(":operating_system", $operating_system, PDO::PARAM_STR); 
} 
else // Update existing entry 
{ 
    //computer_name cpu_speed ram_size mac_address  operating_system 
    $stmt = $pdo->prepare("UPDATE system 
     SET computer_name=:computer_name, 
      cpu_speed=:cpu_speed, 
      ram_size=:ram_size, 
      operating_system=:operating_sytem, 
      mac_address=:mac_address_in 
     WHERE mac_address=:mac_address_query"); 
    echo$stmt->bindValue(":computer_name", $computer_name, PDO::PARAM_STR); 
    echo$stmt->bindValue(":cpu_speed", $cpu_speed, PDO::PARAM_INT); 
    echo$stmt->bindValue(":ram_size", $ram_size, PDO::PARAM_INT); 
    echo$stmt->bindValue(":mac_address_in", $mac_address, PDO::PARAM_STR); 
    echo$stmt->bindValue(":operating_system", $operating_system, PDO::PARAM_STR); 
    echo$stmt->bindValue(":mac_address_query", $mac_address, PDO::PARAM_STR); 
} 

// Execute the command 
$stmt->execute(); 
+0

你爲什麼不在一次查詢中用'ON DUPLICATE KEY UPDATE'來做? – Barmar 2015-03-30 20:36:22

+0

爲什麼你將'mac_address'設置爲它已有的值? – Barmar 2015-03-30 20:39:53

+0

註釋掉所有查詢,但只查找其中一個查找錯誤。 – 2015-03-30 20:39:56

回答

2
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined 

這意味着你有一個參數是沒有定義的。這是接縫,你在這裏有錯誤operating_system=:operating_sytem,可能它應該是operating_system=:operating_system,。這使一個缺少參數,因爲它沒有在這裏設置,因爲你拼錯了一個字。請嘗試檢查prepare聲明中的每個詞以及相應的bindValue

+0

另一個「坐在自己的代碼上坐在電腦前太久」的簡單東西。 Thx :) – Incubbus 2015-03-30 21:35:32

+0

@Incubbus不只是你自己的代碼,我也沒有看到它,而且我通常很注意這些。但是當我說這可能是某個地方的錯字時,我是對的。 – Barmar 2015-03-30 21:45:45

相關問題