Selecting MySQL query via PHP variables

最后都变了- 提交于 2019-12-12 00:12:58

问题


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_rowand $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);

回答1:


$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());

Also, you should consider switching to the PDO library. Among other things, it will help you avoid sql injection attacks in your queries.



来源:https://stackoverflow.com/questions/16001001/selecting-mysql-query-via-php-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!