2016-05-08 74 views
0

以下PHP程序將搜索數據庫中的學生編號,並在找到時顯示詳細信息或在不存在的情況下給出消息。PHP:當條件爲真時While循環不運行

<html> 
<body> 
<?php 

$sno=$_POST['studNo']; 

$connection = mysql_connect("localhost", "root", "") 
    or die("couldn't connect to the server"); 

$db = mysql_select_db("student", $connection) 
    or die("<b>connection fails"); 

$query = "select * from performance where Number = '$sno'"; 

if($result = mysql_query($query)) 
{ 
    echo "<table border = 1 align = center>"; 
    echo "<tr>"; 
    echo "<th>Number<th>Name<th>Address<th>Mobile Number"; 
    echo "</tr>"; 

    while($row = mysql_fetch_array($result)) 
    {   
     echo "<tr>"; 
     echo "<th>",$row['Number'],"</th>"; 
     echo "<th>",$row['Name'],"</th>"; 
     echo "<th>",$row['Address'],"</th>"; 
     echo "<th>",$row['MobileNo'],"</th>"; 
     echo "</tr>"; 
    } 
    echo "</table>"; 
    echo "The student data updated"; 
} 

else 
{ 
    echo "<b>Customer number does not exist"; 
} 

mysql_close($connection); 
?> 
</body> 
</html> 

如果我搜索一個不存在的數字,else塊運行。當我給一個存在的數字,然後if塊運行,但while循環不運行。有人可以幫我嗎?數據庫字段名稱是正確的。

+0

爲什麼',$ row ['Number'],'該字符串與',''連接在一起? –

+0

@FrayneKonok你可以使用它,我覺得看起來很奇怪:) – Dale

+0

警告:你的代碼容易受到[SQL注入攻擊](https://en.wikipedia.org/wiki/SQL_injection)的影響。請閱讀[本文](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)瞭解更多關於如何防止它。 – Pang

回答

0

mysql_query()如果查詢中存在錯誤,則僅返回false。找不到任何匹配的行不是錯誤。要確定是否找到任何行,請使用mysql_num_rows()

$result = mysql_query($query) or die("Query error: " . mysql_error()); 
if (mysql_num_rows($result) > 0) { 
    ... 
} else { 
    echo "<b>Customer number does not exist</b>"; 
} 
+0

非常感謝。有用。 –