我有这个小问题:
我想从数据库中检索一些行,它检索得很好,但是当我在要跟踪的文本字段中插入数据库中不存在的特定值时,它会返回一个空/空白页面,下面是我使用的代码:
<form id="track" name="track" method="post" action="track_now.php">
<h2>Track your shipment Here</h2>
<p><label> Tracking Reference:
<input type="text" id="reference" name="reference" value="" maxlength="40" required="required" /></label></p>
<div class="button_holder">
<p> <input type="submit" id="track" value="Track Now" maxlength="40" required="required" /></label>
</label></p>
</div>
</form>
这就是track_now.php
<form id="track" name="track" method="post" action="">
<h2>Your Shipment Result</h2>
<?php
//error_reporting(0);
$ref = mysql_real_escape_string($_POST['reference']);
// conmnecting to the database
if(isset($ref))
{
$db = mysql_connect('localhost', 'admin', "admin") or die(mysql_error("Cannot Connect to Database"));
mysql_select_db('tracking') or die(mysql_error());
$sql = "SELECT * FROM order_tracking WHERE ship_ref = '".$ref."' ";
$rs = mysql_query($sql);
if($row = mysql_fetch_array($rs)) {
echo '<table width="518" border="1";>';
echo '<tr>';
echo '<td width="137" style="font-size:12px; padding: 5px;" >Shipment Reference: </td>';
echo '<td width="365" style="background-color:#fcfcfc; padding: 10px; font-size:12px;">' . $row['ship_ref'] . "<br />" . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td width="137" style="font-size:12px; padding: 5px;" >Shipment Type: </td>';
echo '<td width="365" style="background-color:#fcfcfc; padding: 10px; font-size:12px;">' . $row['ship_type'] . "<br />" . '</td>';
echo '</tr>';
}
echo "</table>";
}
else if ($rs != $row) {
print 'Invalid Tracking Number, Please <a href="tracking.php"> click here </a> to try again' ;
}
mysql_close();
?>
拜托,我在这里做错了什么?
您的条件可以简化,请尝试以下方式:
if(isset($ref)){
$db = mysql_connect('localhost', 'admin', "admin") or die(mysql_error("Cannot Connect to Database"));
mysql_select_db('tracking') or die(mysql_error());
$sql = "SELECT * FROM order_tracking WHERE ship_ref = '".$ref."' ";
$rs = mysql_query($sql);
if(!rs){
die(mysql_error());
}
if($row = mysql_fetch_array($rs)) {
echo '<table width="518" border="1";>';
echo '<tr>';
echo '<td width="137" style="font-size:12px; padding: 5px;" >Shipment Reference: </td>';
echo '<td width="365" style="background-color:#fcfcfc; padding: 10px; font-size:12px;">' . $row['ship_ref'] . "<br />" . '</td>';
echo '</tr>';
echo '<tr>';
echo '<td width="137" style="font-size:12px; padding: 5px;" >Shipment Type: </td>';
echo '<td width="365" style="background-color:#fcfcfc; padding: 10px; font-size:12px;">' . $row['ship_type'] . "<br />" . '</td>';
echo '</tr>';
echo "</table>";
}
mysql_close();
}
else{
print 'Invalid Tracking Number, Please <a href="tracking.php"> click here </a> to try again' ;
}
因为如果不满足第一个条件else if ($rs != $row)
将具有未定义的值。
正如@marco指出的,您可以在不获取的情况下检查行:
if(mysql_num_rows($rs) > 0){
//found a row
}