【发布时间】:2015-06-04 00:47:35
【问题描述】:
我知道这个问题多次出现,但我在我的代码中找不到错误。在我的更新分支中,每个 $stmt->bindValue(...) 返回 TRUE,但我捕获了 pdo 异常
SQLSTATE[HY093]:参数号无效:参数未定义
插入新条目可以正常工作。
在我的mysql数据库中,表'system'的结构是:
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();
【问题讨论】:
-
你为什么不用
ON DUPLICATE KEY UPDATE在一个查询中做呢? -
为什么要将
mac_address设置为它已有的值? -
注释掉除一个以外的所有查询以找出三个中的哪一个引发错误。
-
@GentiSaliu 他说他知道是哪一个导致了错误,它是
UPDATE。 -
这是代码的逐字副本吗?可能有错字,如果您在此处重新输入,您可能在此过程中已更正。