$stmt = $conn->prepare("INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',:cover,:dateofbirthYear:dateofbirthMonth:dateofbirthDay,NOW(),:sex,:country)");
$stmt->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':cover' => $cover,
':dateofbirthYear' => $dateofbirthYear,
':dateofbirthMonth' => $dateofbirthMonth,
':dateofbirthDay' => $dateofbirthDay,
':sex' => $sex,
':country' => $country
));
由于某种原因,此insert语句不起作用。我是PDO的新手,所以我对它不太了解。我做错了什么?
这个陈述给了我这个错误:
致命错误:带有消息'SQLSTATE [HY093]的未捕获异常'PDOException':无效参数编号:绑定变量数与/home/manga/public_html/new/register.php:80中的标记数不匹配跟踪:
#0 /home/manga/public_html/new/register.php(80):PDOStatement->执行(数组)
在第80行的/home/manga/public_html/new/register.php中抛出#1 {main}
答案 0 :(得分:6)
您以错误的方式准备了查询
INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',
:cover,:dateofbirthYear:dateofbirthMonth:dateofbirthDay,NOW(),:sex,:country
// ^ These need to either single or separated
对于你正在尝试的东西,你可以这样做
//Prepare the date of birth earlier
$dob = $dateofbirthYear.$dateofbirthMonth.$dateofbirthDay;
//Then pass it as a single $variable
$stmt = $conn->prepare("INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',:cover,:dob,NOW(),:sex,:country)");
$stmt->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':cover' => $cover,
':dob' => $dob, // <-- Problem solved
':sex' => $sex,
':country' => $country
));
// Then it will execute
答案 1 :(得分:2)
您的确切错误消息是:
SQLSTATE [HY093]:参数号无效:绑定变量数与令牌数不匹配
这意味着您传递的参数的数量/名称(array()
中的execute
)与您在prepare()
SQL中的参数的数量/名称不匹配查询。
如果你compare that with the other questions that contain SQLSTATE[HY093]
,你会发现它经常与大而且格式不好的代码有关,难以阅读。这使得很难计算。然后你对某些事情进行了监督,然后发生了错误。
只需修复并完成,例如,您无法从三个名称中创建一个参数:
,:dateofbirthYear:dateofbirthMonth:dateofbirthDay,
而是只为生日传递一个参数:
, :dateofbirth,
您还可以使代码更具可读性:
$stmt = $conn->prepare(
"INSERT INTO user
VALUES (
'', :username, md5(:password), '', 1, '', '', :email, '', 0, 0, '',
:cover, :dateofbirth, NOW(), :sex, :country
)"
);
$stmt->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':cover' => $cover,
':dateofbirth' => $dateofbirthYear . $dateofbirthMonth . $dateofbirthDay,
':sex' => $sex,
':country' => $country
));
然后您遇到密码哈希的安全问题:
md5(:password)
请执行正确的密码哈希,请参阅PHP FAQ about Safe Password Hashing。
答案 2 :(得分:-2)
更正准备好的查询:
$stmt = $conn->prepare("INSERT INTO user VALUES ('',:username,md5(:password),'',1,'','',:email,'',0,0,'',:cover,:dateofbirthYear,:dateofbirthMonth:,dateofbirthDay,NOW(),:sex,:country)");
//:dateofbirthYear,:dateofbirthMonth:,dateofbirthDay place holders are seprated
$stmt->execute(array(
':username' => $username,
':password' => $password,
':email' => $email,
':cover' => $cover,
':dateofbirthYear' => $dateofbirthYear,
':dateofbirthMonth' => $dateofbirthMonth,
':dateofbirthDay' => $dateofbirthDay,
':sex' => $sex,
':country' => $country
));