我很抱歉,这是一个愚蠢的问题,但是由于我是Web语言和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 injection,指南: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

08-04 16:21