簡體   English   中英

在搜索表中顯示結果 (PHP)

[英]Displaying results in a search table (PHP)

之前可能已經問過這個問題,請隨時鏈接我或其他什么,我只是找不到我想要的確切內容。

這很簡單,我需要顯示搜索表單的結果。 那部分很簡單,我可以讓它發揮作用。 我遇到的問題是當沒有結果與用戶搜索的內容匹配時。

我很確定我只需要使用 IF 語句,但我對 PHP 不是很熟悉,無法弄清楚如何正確顯示代碼。

這是我到目前為止:

$query = "SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'";

if (!$query)
{
    echo "No results found in the database. Please go back and search again.";
}

我的問題是:當用戶搜索與數據庫中的任何內容都不匹配時,如何顯示“未找到結果...”消息?

注意- 在嘗試理解 PHP 和 SQL 中的某些術語時,我很快就會感到非常困惑,所以請嘗試像對絕對初學者一樣解釋您的答案。

提前謝謝了。

您希望在數據庫表中未找到任何行時顯示“未找到結果”消息。

為此,您可以使用以下 PHP 和 SQL 代碼:

$sql = "SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'";
$query = $db->prepare($sql);
$query->execute();
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) { 
    // Row exists
} else {
    echo "No results found in the database. Please go back and search again.";
}

請注意,上述答案容易受到 SQL 注入攻擊。 為了防止SQL注入攻擊,建議您准備並綁定所有用戶提交的數據,這里有一個更好的例子來說明如何防止SQL注入攻擊:(完整示例,包括數據庫連接)

$db = new PDO($dsn);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = $db->prepare("SELECT * FROM search WHERE isbn=:isbn OR bookname=:bookname OR author=:author OR category=:category");
$query->execute([ ':isbn'=>$isbn, ':bookname'=>$bookname, ':author'=>$author, ':category'=>$category ]);
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) { 
    // Row exists
} else {
    echo "No results found in the database. Please go back and search again.";
}

假設您使用的是Mysqli

  //connect with mysql
    $conn = mysqli_connect("localhost", "user", "password", "db");
   //here is the query
    if($result = mysqli_query($conn,"SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'")){
       if(mysqli_num_rows($result) > 0){
          //mysqli_num_rows() returns the number of rows in a result . 
          //when it is greater than zero, it has some results 
       }
       else{
         echo "No results found in the database. Please go back and search again.";
         //Do something if no results returned
       }
    }
    //finally free the results
    mysqli_free_result($result);
mysqli_close($conn);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM