我正在學習PHP,並正在開發一個用於在MySQL數據庫中搜索書籍的項目。用戶應該能夠通過書名,書的作者和類別進行搜索,利用一切,一個或的3PHP使用多個文本框搜索多列的MySQL搜索
目前這裏的任何組合是我的代碼:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to Library Management System</title>
<link href="main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
require_once "db.php";
include "header.html";
if(isset($_POST["bookTitle"]))
{
$bookTitle = mysqli_real_escape_string($con, $_POST["bookTitle"]);
}
else
{
$bookTitle = NULL;
}
if(isset($_POST["bookAuthor"]))
{
$bookAuthor = mysqli_real_escape_string($con, $_POST["bookAuthor"]);
}
else
{
$bookAuthor = NULL;
}
if(isset($_POST["category"]))
{
$category = mysqli_real_escape_string($con, $_POST["category"]);
}
else
{
$category= NULL;
}
echo "Results by Book Title Search";
$bookTitle = mysqli_real_escape_string($con, $_POST["bookTitle"]);
$query = "Select * From book NATURAL JOIN category where category.CategoryDesc LIKE '%" .$category ."%' OR book.BookTitle LIKE '%" .$bookTitle ."%' OR book.Author LIKE '%" .$bookAuthor."%'";
$result=mysqli_query($con, $query) or die(mysqli_error());
echo '<table border="1" width="95%">'."\n";
echo "<tr><th>ISBN</th><th>Title</th><th>Author</th><th>Edition</th><th>Year</th><th>Category ID</th><th>Reserved</th><th>Reserve?</th><tr>";
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<tr><td>";
echo(htmlentities($row[0]));
echo("</td><td>");
echo(htmlentities($row[1]));
echo("</td><td>");
echo(htmlentities($row[2]));
echo("</td><td>\n");
echo(htmlentities($row[3]));
echo("</td><td>\n");
echo(htmlentities($row[4]));
echo("</td><td>\n");
echo(htmlentities($row[5]));
echo("</td><td>\n");
echo(htmlentities($row[6]));
echo("</td><td>\n");
echo('<a href="edit.php?id='.htmlentities($row[1]).'">Edit</a>
/');
echo('<a
href="delete.php?id='.htmlentities($row[1]).'">Delete</a>');
echo("</td></tr>\n");
}
echo "</br>";
如果我搜索使用全部三個字段,查詢返回相關結果。如果一個或多個字段留空,則返回整個數據庫,這不是我想要的。
有沒有更好的方法呢?
感謝您的答覆。我在該代碼的第一個IF行出現「致命錯誤:無法在寫入上下文中使用函數返回值」錯誤。 – MickyMcG
使用更新後的版本,對於您之前的代碼遇到的問題感到抱歉。 –
當我使用這段代碼時,搜索完全沒有結果。 – MickyMcG