該場景是必須搜索代碼,並且如果代碼存在,結果將從MySQL DB中顯示,否則顯示消息「對不起,但沒有找到結果「顯示。也許沒有重新輸入您的EVR:或仔細檢查您的輸入。」PHP:變量顯示值,即使提交按鈕沒有被點擊
然而,搜索還送之前,已經出現該錯誤消息。
我在做什麼錯?
<?php
$no_results = NULL;
$query = (isset($_POST['query']) ? $_POST['query'] : null);
$raw_results = mysql_query("SELECT * FROM evrdata WHERE evr_no = '$query'") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
$evr_no ='<br/>EVR No. : '.'<b>'.$results['evr_no'].'</b>';
$surname ='<br/>Surname : '.'<b>'.$results['surname'].'</b>';
$othername ='<br/>First Names : '.'<b>'.$results['othername'].'</b>';
$ps_code ='<br/>PS Code : '.'<b>'.$results['ps_code'].'</b>';
}
}
else { // if there is no matching rows do following
$no_results = '<br/>Sorry, but there were no results found. Perhaps re-enter your EVR No.: or double check your entry.</b>';
}
?>
,並在同一個文件,在HTML當結果出現:
<form action="index.php" method="POST" class="search">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<input type="text" name="query" class="form-control" placeholder="Enter Your EVR No." required/>
<button type="submit" id="form-submit" value="Search" class="btn-submit btn btn-big dark-blue-bordered-btn">Submit</button>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<?php
if($no_results!="") // Two times Doule Quotation marks that is, and != means "not equal to". So we mean to say if $code is not equal to empty
{
echo $no_results;
}
else { echo " "; }
我曾嘗試isset()函數,空(),但錯誤信息仍顯示,即使搜尋未麻德。
我錯過了什麼?
**停止**使用不推薦的'mysql_ *'API。使用'mysqli_ *'或'PDO' – Jens
$ _POST ['query']最可能是空的。因此SQL查詢失敗。創建一個圍繞整個SQL的if子句,將它添加到$ query行之前。如果設置$ _POST ['query']並且post ['query']的strlen不爲空,繼續。 – Janno
是的,直到提交按鈕被點擊。可以做什麼來防止這種情況? – SQDawq