繁体   English   中英

与名称中包含撇号的名称匹配

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM