我有以下PHP代码,用于在给定用户名的用户名字段为空的情况下插入数据,或者如果存在用户名则更新数据。目前,插入以前工作正常,但它永远不会切换到更新子句。
然而,现在,insert子句无法识别我的测试变量,没有明显的原因。我得到的错误是:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
和
Notice: Undefined variable: checkUsername
这是最近的。
if($cmd=="submitinfo"){
$usernameQuery = "select username from USERS where username = $username";
$xblah = $con->query($usernameQuery);
while ($row = mysqli_fetch_assoc($xblah))
{
$checkUsername = $row['username'];
}
if ($checkUsername == null) {
$userQuery = "INSERT INTO USERS VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($userInfo = $con->prepare($userQuery)) {
$userInfo->bind_param("ssssssssssssssssssss", $username, $firstname, $lastname, $flaggedauctions, $lastauction, $street1, $city1, $postcode1, $street2, $city2, $postcode2, $phone, $mobilephone, $fax, $email, $website, $bank, $banknumber, $accountnumber, $comments);
$userInfo->execute();
$userInfo->close();
echo "true";
} else {
echo "false";
}
print_r($con->error);
}
else if ($checkUsername == $username) {
$userQuery = "UPDATE USERS SET firstname = ?, lastname = ?, flaggedauctions = ?, lastauction = ?, street1 = ?, city1 = ?, postcode1 = ?, street2 = ?, city2 = ?, postcode2 = ?, phone = ?, mobilephone = ?, fax = ?, email = ?, website = ?, bank = ?, banknumber = ?, accoutnumber = ? WHERE username = ?";
if ($userInfo = $con->prepare($userQuery)) {
$userInfo->bind_param("sssssssssssssssssss", $firstname, $lastname, $flaggedauctions, $lastauction, $street1, $city1, $postcode1, $street2, $city2, $postcode2, $phone, $mobilephone, $fax, $email, $website, $bank, $banknumber, $accountnumber, $username);
$userInfo->execute();
$userInfo->close();
echo "true";
} else {
echo "false";
}
print_r($con->error);
}
}
根据与用户名字段匹配的$ username的内容,执行更新或插入的首选方式是什么?
答案 0 :(得分:1)
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
那是你的错误信息?我认为你的问题就在这一行:
$xblah = $con->query($usernameQuery);
在$ xblah上做var_dump
。我怀疑你的查询失败了。可能是因为您没有从输入中提取$username
。而对于爱的根,一定要逃避它! mysql_real_escape_string()
会做你想做的事。
答案 1 :(得分:0)
如果您使用的是MySQL且用户名是唯一的,则可以使用这个方便的SQL:
INSERT INTO users (?, ?, ...) ON
DUPLICATE KEY UPDATE firstname=?,
lastname=?, ...)
有关完整文档,请参阅http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html。