[英]matching with name containing apostrophe in php
我有一個查詢要匹配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
我錯過了什么嗎?
由於我們已經討論了在注釋中更改為准備好的語句,因此您可以執行以下操作(這是面向對象的方法,與較舊的過程方法分開):
// 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
遍歷行並實際分配變量,因為我認為這樣可以更bind_result
,更輕松地跟蹤何時有很多代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.