WHERE 子句 MySQL 中的 PHP 字符串变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15684465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:44:31  来源:igfitidea点击:

PHP string variable in WHERE clause MySQL

phpmysqlsqlselect

提问by Akis Wma Asimakopoulos

I am having a problem with this simple sql query:

这个简单的 sql 查询有问题:

<?php 
require_once('../../Connections/tohoshows.php'); 

$show ='gothaf';

mysql_select_db($database_tohoshows, $tohoshows);
$query_getShows = "SELECT * FROM toho_shows WHERE toho_shows.show =' ". $show. " '";
$getShows = mysql_query($query_getShows, $tohoshows) or die(mysql_error());
$row_getShows = mysql_fetch_assoc($getShows);
$totalRows_getShows = mysql_num_rows($getShows);

mysql_free_result($getShows);
?>

When I use the string directly in the WHERE clause like this

当我像这样直接在 WHERE 子句中使用字符串时

 $query_getShows = "SELECT * FROM toho_shows WHERE toho_shows.show ='gothaf'";

I get a result. When I use the variable instead, I get no data! I am a novice and I can't figure out what am I doing wrong. Any help would be appreciated. Thank you!

我得到一个结果。当我使用变量时,我没有得到任何数据!我是新手,我无法弄清楚我做错了什么。任何帮助,将不胜感激。谢谢!

回答by John Woo

you getting no date because you have extra space betwee the quotes,

你没有约会,因为你在引号之间有额外的空间,

$query_getShows = "SELECT * FROM toho_shows WHERE toho_shows.show =' ". $show. " '";
                                                                    ^ HERE      ^

which will then be parsed into

然后将被解析为

SELECT * FROM toho_shows WHERE toho_shows.show =' gothaf '


remove it and it will work

删除它,它会工作

$query_getShows = "SELECT * FROM toho_shows WHERE toho_shows.show ='". $show. "'";

As a sidenote, the query is vulnerable with SQL Injectionif the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatementsyou can get rid of using single quotes around values.

作为一个旁注,查询是脆弱的SQL Injection,如果值(小号变量)从外面走了进来。请查看下面的文章,了解如何预防。通过使用,PreparedStatements您可以摆脱在值周围使用单引号。