簡體   English   中英

php mysql查詢返回true,即使設置為空

[英]php mysql query returns true even when empty set

我有一個表單,該表單使用html表單從用戶那里獲取一個value(id),並在名為“ account”的數據庫中查找它以顯示所有值。 如果用戶輸入的值在數據庫中不存在,則應顯示警報。

//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);
?>

我的問題是,當我輸入數據庫中不存在的id的值時,它沒有輸入else塊並顯示警報。 那么,為什么查詢對所有值都返回true?

如果查詢成功, mysql_query()將返回true,即使沒有返回結果。 您想使用mysql_num_rows檢查是否返回任何行。

另外,您應該真正開始對數據庫查詢使用PDO或mysqli。 不像mysql_函數那樣不被棄用,它的安全性要高得多。

http://us2.php.net/manual/zh/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);
?>

對於SELECT,SHOW,DESCRIBE,EXPLAIN和其他返回結果集的語句,mysql_query()成功時返回資源,錯誤時返回FALSE。

SQL語句,INSERT,UPDATE,DELETE,DROP等,mysql_query()成功返回TRUE,錯誤返回FALSE。

要檢查是否有返回的行,您需要使用

mysql_num_rows()

您還使用了不推薦使用的mysql_函數。

您應該使用准備好的語句啟動mysqli_ or PDO

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

它應該是

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM