duangeli1334 2015-02-13 21:45
浏览 24
已采纳

我怎样才能在MySQL数据库表中找不到数据的php代码?

I am so sorry mybe it is a silly question but as I am new in web language and php I dont know how to solve this problem.

I have a code which is getting ID from user and then connecting to MySQL and get data of that ID number from database table and then show on webpage.

But I would like to what should I add to this code if user enter an ID which is not in table of database shows a message that no data found.

Here is my code:

<?php

//connect to the server
$connect = mysql_connect ("localhost","Test","Test") ;

//connection to the database
mysql_select_db ("Test") ;

//query the database
$ID = $_GET['Textbox'];
$query = mysql_query (" SELECT * FROM track WHERE Code = ('$ID') ");

//fetch the results / convert results into an array
$ID = $_GET['Textbox'];

WHILE($rows = mysql_fetch_array($query)) :

     $ID = 'ID';

  echo "<p style=\"font-color: #ff0000;\"> $ID </p>";


  endwhile;

?>

Thank You.

Sorry if it is so silly question.

  • 写回答

1条回答 默认 最新

  • dousu1916 2015-02-13 22:01
    关注

    You should use PDO (great tutorial here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ). This way, you can develop safer applications easier. You need to prepare the ID before inserting it to the query string, to avoid any user manipulation of the mysql query (it is called sql injection, guide: http://www.w3schools.com/sql/sql_injection.asp ).

    The main answer to your question, after getting the results, you check if there is any row in the result, if you got no result, then there is no such an ID in the database. If you use PDO statements $stmt->rowCount();.

    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
    
    $stmt = $db->prepare("SELECT * FROM table WHERE Code=?");
    $stmt->bindValue(1, $id, PDO::PARAM_INT); // or  PDO::PARAM_STR
    $stmt->execute();
    
    $row_count = $stmt->rowCount();
    
    if ($row_count > 0) {
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        //results are in $results
    } else {
        // no result, no such an ID, return the error to the user here.
    }
    

    Another reason to not use mysql_* functions: http://php.net/manual/en/migration55.deprecated.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错