Selecting MySQL query via PHP variables

2019-08-22 04:07发布

问题:

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.