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