简体   繁体   中英

php/sql AND statement not working

I have my code:

$db_date2;
$today2 = date("Y-m-d");
        $sql1 = "SELECT * FROM todays_spend WHERE id =$user_id_session AND date=$today2";
        $date_records = mysql_query($sql1); 
        while($today_trip=mysql_fetch_assoc($date_records)){
        $db_date2 = $today_trip['date'];    
        }
        echo $db_date2;

It is saying "Undefined variable: db_date2". When I remove the AND statement it works. Am I doing the AND statement wrong? the 'date' field in my database is also saved in the format Ymd.

also tried the single qoutes '' around the variables, still not working!

You need to write single quote '' around your variable.

Write your query as below:-

$sql1 = "SELECT * FROM todays_spend WHERE id ='$user_id_session' AND date='$today2'";

Warning

mysql_* was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used

Hope it will help you :-)

Actually it is using your variables as string in the query rather than their values so Just replace your code with the following:

$db_date2;
$today2 = date("Y-m-d");
        $sql1 =     
        $sql1 = "SELECT * FROM todays_spend WHERE id ='".$user_id_session."' AND date='".$today2."'";
        $date_records = mysql_query($sql1); 
        while($today_trip=mysql_fetch_assoc($date_records)){
        $db_date2 = $today_trip['date'];    
        }
        echo $db_date2;

For your variables, you'll need single quotes:

This:

$sql1 = "SELECT * FROM todays_spend WHERE id =$user_id_session AND date=$today2";

Should be:

$sql1 = "SELECT * FROM todays_spend WHERE id ='$user_id_session' AND date='$today2'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM