[英]Variables in PDO-parameters and -queries
我有多个if和elseif语句,如下所示:
if ($str == "CARS") {
$first = $db->prepare('INSERT INTO table_CAR (id_CAR, anything) VALUES (:id_CAR, :anything) ON DUPLICATE KEY UPDATE id_CAR = LAST_INSERT_ID(id_CAR)');
$first->bindParam(':id_CAR', $null = null, PDO::PARAM_NULL);
$first->bindParam(':anything', $anything, PDO::PARAM_STR);
$first->execute();
}
else if ($str == "PLANES") {
$first = $db->prepare('INSERT INTO table_PLANES (id_PLANES, anything) VALUES (:id_PLANES, :anything) ON DUPLICATE KEY UPDATE id_PLANES = LAST_INSERT_ID(id_PLANES)');
$first->bindParam(':id_PLANES', $null = null, PDO::PARAM_NULL);
$first->bindParam(':anything', $anything, PDO::PARAM_STR);
$first->execute();
}
现在,我想发挥作用,因为它也做了同样的事情。 唯一的区别是名称。 但是如何将这些词(CAR和PLANES)放入变量中? 我的问题是,这些词是查询和参数的一部分,而且并不总是相同的(CARS!= CAR)。
您始终可以始终先在变量中构造sql查询:
function insert($table, $anything) {
// check $table using a whitelist to prevent SQL injections!
$sql = 'INSERT INTO table_' . $table . ' (anything) VALUES (:anything)';
$first->bindParam(':anything', $anything, PDO::PARAM_STR);
$first->execute();
}
如您所见,我稍微整理了一下查询。 无需为AUTO_INCREMENT
字段插入NULL值,因为MySQL会为您插入正确的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.