简体   繁体   中英

php mysql query returns true even when empty set

I have a form that takes a value(id) from the user using html form and looks for it in the database called "account" to display all values. If the value entered by the user doesn't exist in the database, it should display an alert.

//user_form.html

    <html>
    <form method="get" action="user_action.php">
    <input type="text" name="val"/>
    <input type="submit" value="Enter"/>
    </form>
    </html>

//user_action.php
<?php
    $name=$_GET["val"];
    $con = mysql_connect("localhost","my_username","my_password") or die('Could not connect: ' . mysql_error());
    mysql_select_db("account",$con);
    if( ($result=mysql_query("select * from my_table where id=$name")) )
        //display the database table
    else
       echo '<script type="text/javascript">alert("Id not found in database!");</script>';
    mysql_close($con);
?>

My problem is when I enter a value for id that doesn't exist in the database, it doesn't enter the else block and display the alert. So, why is the query returning true for all values?

mysql_query() will return true if the query is successful, even if no results are returned. You want to use mysql_num_rows to check if any rows are returned.

Also, you should really start using PDO or mysqli for your database queries. It's a lot more secure is not not deprecated unlike mysql_ functions.

http://us2.php.net/manual/en/ref.pdo-mysql.php

<?php
    $name=$_GET["val"];
    $con = mysql_connect("localhost","my_username","my_password") or die('Could not connect: ' . mysql_error());
    mysql_select_db("account",$con);
    if( ($result=mysql_query("select * from my_table where id=$name")) ) {
       if(mysql_num_rows($result)) {
         // Rows Returned
       }else{
          echo '<script type="text/javascript">alert("Id not found in database!");</script>';
       }
    } else {
      // Mysql Error (Error with Query)   
    }
    mysql_close($con);
?>

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

To check if there are rows returned you need to use

mysql_num_rows()

More over you are using deprecated mysql_ function.

You should start mysqli_ or PDO with prepared statement.

if( ($result=mysql_query("select * from my_table where id=$name")) )

它应该是

if( ($result==mysql_query("select * from my_table where id=$name")) )

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