我有一个查询,我希望匹配fname和lname
$result = $mysqli->query('SELECT * FROM user WHERE userId = "'.$_SESSION["userId"].'" AND FriendFirstName = "'.htmlentities($firstName, ENT_QUOTES,"UTF-8").'" AND FriendLastName = "'.htmlentities($lastName, ENT_QUOTES,"UTF-8").'" AND FriendStatusCode="verified" AND friendId!='.$fid.' AND ViewableRow <> "0" ') or die($mysqli->error);
echo 'SELECT * FROM user WHERE userId = "'.$_SESSION["userId"].'" AND FriendFirstName = "'.htmlentities($firstName, ENT_QUOTES,"UTF-8").'" AND FriendLastName = "'.htmlentities($lastName, ENT_QUOTES,"UTF-8").'" AND FriendStatusCode="verified" AND friendId!='.$fid.' AND ViewableRow <> "0" ';
如果我有一个名字John'y那么它不会产生任何结果,它不会返回任何行,我回应了查询,如果我运行相同的查询,我得到的结果是我的SQL。
输出变得像这样
SELECT *
FROM user_friend_detail
WHERE userId = "9306" AND FriendFirstName = "Aa\'tid"
AND FriendLastName = "Kenddy"
AND FriendStatusCode="verified" AND friendId!=9366 AND ViewableRow "0"
并返回mysql中的行。我关掉了魔术引号,我认为它是一个非常简单的问题,但它浪费了我很多时间。
The FNAME is Aa'tid
The lname is Kenddy
我错过了什么吗?
答案 0 :(得分:0)
由于我们已经讨论过在评论中更改为准备好的语句,这里是你可以做的(这是面向对象的方法,与旧的程序方法分开):
// this code will use the following variables that you must set somewhere before running your query:
// $firstName
// $lastName
// $fid
// it also uses:
// $_SESSION["userId"]
// connect to the database (fill in values for your database below)
$mysqli = new mysqli('host','username','password','default database');
// build query with parameters
$query = "SELECT * FROM user WHERE userId = ? AND FriendFirstName = ? AND FriendLastName = ? AND FriendStatusCode='verified' AND friendId != ? AND ViewableRow <> '0'";
// prepare statement
if ($stmt = $mysqli->prepare($query)) {
// bind parameters
$stmt->bind_param("issi", $_SESSION['userId'], $firstName, $lastName, $fid);
// execute statement
$stmt->execute();
// set the variables to use to store the values of the results for each row (I made the variables up, in this case, let's assume your query returns 3 columns, `userId`, `firstName`, and `lastName`)
$stmt->bind_result($returnUserId, $returnFirstName, $returnLastName);
// loop through each row
while ($stmt->fetch()) {
// output the variables being looped through
printf ("%d: %s %s\n", $returnUserId, $returnFirstName, $returnLastName);
}
// close statement
$stmt->close();
}
// close connection
$mysqli->close();
此示例不使用错误处理,但它应该。还有很多其他方法可以使用结果集(例如关联数组),您可以查看要使用的文档。在这个例子中,我使用bind_result
循环遍历行并实际分配变量,因为我相信它更清晰,更容易跟踪你有很多代码。