尝试动态生成和执行sql查询时出错。我仔细检查了执行的查询,一切看起来都很好,但我仍然得到这个错误。我做错什么了?
php警告:pdostatement::execute():sqlstate[hy093]:无效参数号:绑定变量的数量与令牌的数量不匹配
代码如下:
$data = array();
$params = [
'planid' => $_POST['planid'],
'email' => $_POST['email'],
'firstname' => $_POST['firstname'],
'lastname' => $_POST['lastname']
];
foreach ($params as $key => $value) {
$data[':'.$key] = $value;
}
print_r($data);
//OUTPUT:
Array
(
[:planid] => GBP001
[:email] => juandelacruz@myemail.com
[:firstname] => Juan
[:lastname] => De La Cruz
)
$sql = "INSERT INTO user (";
$count = count($params);
$x=1;
foreach ($params as $k => $v) {
$sql .= " $k ";
if($x<$count)
$sql .= ",";
$x++;
}
$sql .= " ) SELECT ";
$y=1;
foreach ($params as $k => $v) {
$sql .= " :$k ";
if($y<$count)
$sql .= ",";
$y++;
}
$sql .= " FROM DUAL WHERE NOT EXISTS( SELECT * FROM user u
WHERE u.email = :email AND u.planid = :planId )";
var_dump($sql);
//OUTPUT:
INSERT INTO user ( planid , email , firstname , lastname ) SELECT :planid , :email , :firstname , :lastname FROM DUAL WHERE NOT EXISTS( SELECT * FROM user u WHERE u.email= :email AND u.planid = :planId)
$pdo = Database::getInstance();
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
print_r($stmt);
//OUTPUT:
PDOStatement Object
(
[queryString] => INSERT INTO user ( planid , email , firstname , lastname ) SELECT :planid , :email , :firstname , :lastname FROM DUAL WHERE NOT EXISTS(SELECT * FROM user u
WHERE u.email= :email AND u.planid = :planid)
)
暂无答案!
目前还没有任何答案,快来回答吧!