我知道这个问题出现过多次,但我在代码中找不到错误。在我的更新分支中,每个$stmt->bindValue(…)都返回TRUE,但我捕捉到了pdo异常
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();
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
这意味着您有一个未定义的参数。这里有错误的接缝operating_system=:operating_sytem,
可能应该是operating_system=:operating_system,
。这使得一个参数丢失,因为您拼错了一个单词,所以没有在此处设置该参数。请尝试检查prepare
语句中的每个单词和相应的bindValue
。