0

我有一个查询,我想在其中匹配 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

我错过了什么吗?

4

1 回答 1

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循环遍历行并实际分配变量,因为我相信当你有很多代码时它会更清晰,更容易跟踪。

于 2013-12-18T19:18:54.843 回答