通过PHP变量选择MySQL查询 [英] Selecting MySQL query via PHP variables
问题描述
我在$booked_num
中得到零,我尝试在SQL中使用值代替变量的查询,它工作正常.但是我不知道我在哪里犯错,请帮忙.
我已经回显了每个变量,并且一切都很好,但是$booked_row
中没有任何内容,而$booked_num
却回显了零.
I am getting zero in $booked_num
, I tried the query in SQL with values in place of variables, it worked fine. But I don't know where I am making a mistake, please help.
I already echoed every variable and everything is fine, but nothing is there in $booked_row
and $booked_num
is echoing zero.
require_once 'mysql_connector.php';
$booked_result = mysql_query('select * from booked where train_no = ".$train_no." and date = ".$date." and st_from = ".$st_from." and st_to = ".$st_to.";') or die(mysql_error()) ;
$booked_num = mysql_num_rows($booked_result);
echo $booked_num;
$booked_row = mysql_fetch_array($booked_result,MYSQL_ASSOC);
print_r($booked_row);
推荐答案
$booked_result = mysql_query('select * from booked where train_no = ".$train_no." and date = ".$date." and st_from = ".$st_from." and st_to = ".$st_to.";') or die(mysql_error()) ;
此语法不正确-您需要在连接变量之前关闭字符串. 像这样:
This syntax is incorrect - you need to close the string before concatenating variables. Something like:
$booked_result = mysql_query('select * from booked where train_no = "' .$train_no. '" and date = "' .$date. '" and st_from = "' .$st_from. '" and st_to = "' .$st_to. '";') or die(mysql_error());
此外,您应该考虑切换到PDO库.除其他外,它将帮助您避免查询中的SQL注入攻击.
Also, you should consider switching to the PDO library. Among other things, it will help you avoid sql injection attacks in your queries.
这篇关于通过PHP变量选择MySQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!