如何为 select 查询转义 php 变量中的撇号

How to escape apostrophe in php variable for select query

我尝试使用 mysqli_real_escape_string 变量值来自数据库来转义查询字符串和包含撇号的 $variable。我收到以下错误。

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'Shamrock Rovers%\' AND away_team like \'St Patrick's Athletic%\'' at line 1

撇号没有被比较值周围的引号转义。

这是 PHP 文件中出现的查询:

    $homeTeam = filter_input(INPUT_GET, 'homeTeam', FILTER_SANITIZE_STRING);
    $homePlayers = "select * from players where team_name like $homeTeam";
    $homePlayers = mysqli_real_escape_string($dbc, $homePlayers);
    $homePlayersResult = mysqli_query($dbc, $homePlayers);

然后echo输出到浏览器:

    select * from players where team_name like Shamrock Rovers

我尝试了多种不同的方法,结果没有变化,我觉得我忽略了一些简单的事情。 提前致谢。

编辑 1

更新代码

$homeTeam = filter_input(INPUT_GET, 'homeTeam', FILTER_SANITIZE_STRING);          
$homeTeam = mysqli_real_escape_string($dbc, $homeTeam);
echo "<br>".$homeTeam."<br>";
$homePlayers = "select * from players where team_name like '$homeTeam%'";

$homePlayersResult = mysqli_query($dbc, $homePlayers);

此脚本从处理脚本接收 3 个参数

header("location: ../scorer.php?gameWeek=$gameWeek&homeTeam=$homeTeam&awayTeam=$awayTeam");

输出 select * 来自 team_name 喜欢“St Patrick's Athletic%”的球员

编辑 2

在 mysql 命令中输入查询后 window 当我提交一次查询时没有任何反应,但是当我再次输入时我得到以下错误。

like $homeTeam";

您需要引用该变量。

like '$homeTeam'";

like '$homeTeam%'";

因为这是一个字符串,根据您的 like Shamrock Rovers

不过我不知道你为什么要用

$homePlayers = mysqli_real_escape_string($dbc, $homePlayers);
                                               ^^^^^^^^^^^^

在转义您的查询时:(?)

$homePlayers = "select * from players where team_name like $homeTeam";
^^^^^^^^^^^^

您可能打算使用:

$homePlayers = mysqli_real_escape_string($dbc, $homeTeam);


编辑:(测试)

这是我用来成功查询我的测试table的,"users"。

<?php

$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';

$Link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($Link->connect_errno > 0) {
  die('Connection failed [' . $Link->connect_error . ']');
}

$_GET['homeTeam'] = "St Patrick's Athletic";

$username = $_GET['homeTeam'];

$homeTeam = filter_input(INPUT_GET, 'homeTeam', FILTER_SANITIZE_STRING);
$homePlayers = mysqli_real_escape_string($Link, $homeTeam);
$homePlayers = "select * from users where username like '$homeTeam%'";
$homePlayersResult = mysqli_query($Link, $homePlayers);

echo "Names found like: " . $username;

echo "<br>";

 while($row = mysqli_fetch_array($homePlayersResult)){

echo $row['username'];

echo "<br>";

echo "<a href=\"{$row['my_row']}\">".$row['my_row']."</a>";

echo "<br>";

}
  • 此外,请确保您的列确实是 VARCHAR 且其长度足够长,并且您的输入是 "text type".

旁注:

你不需要这个会破坏你的查询:

$homeTeam = filter_input(INPUT_GET, 'homeTeam', FILTER_SANITIZE_STRING);

因为您已经在使用 mysqli_real_escape_string() 来清理您的输入。

我们在聊天中讨论过的事情已经解决了,但我在聊天之前已经提到了以上,这毕竟是解决方案。