2016-05-08 4 views
0

次のPHPプログラムは、データベース内の受講番号を検索し、見つかった場合は詳細を表示し、存在しない場合はメッセージを表示します。PHP:条件がtrueのときにループが実行されない

<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)に脆弱です。それを防ぐ方法の詳細については、[this post](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

ありがとうございました。できます。 –

関連する問題