繁体   English   中英

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

[英]How can I write a php code for data can not find in table of MySQL database?

我很抱歉mybe这是一个愚蠢的问题,但由于我是网络语言和PHP的新手,我不知道如何解决这个问题。

我有一个代码,它从用户获取ID,然后连接到MySQL并从数据库表中获取该ID号的数据,然后显示在网页上。

但是,如果用户输入不在数据库表中的ID显示没有找到数据的消息,我想如何添加到此代码中。

这是我的代码:

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

?>

谢谢。

对不起,如果它是如此愚蠢的问题。

您应该使用PDO(这里有很棒的教程: http//wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers )。 这样,您就可以更轻松地开发更安全的应用程序。 您需要在将ID插入查询字符串之前准备ID,以避免任何用户操作mysql查询(它被称为sql注入,指南: http//www.w3schools.com/sql/sql_injection.asp )。

对你的问题的主要答案,在得到结果后,检查结果中是否有任何行,如果没有结果,那么数据库中就没有这样的ID。 如果使用PDO语句$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.
}

不使用mysql_ *函数的另一个原因: http ://php.net/manual/en/migration55.deprecated.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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