我正在学习PHP并且正在开发一个用于在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>";
如果我使用所有三个字段进行搜索,查询将返回相关结果。如果一个或多个字段留空,则返回整个数据库,这不是我想要的。
有更好的方法吗?
答案 0 :(得分:2)
你可以用这个
$condition="sasaaa";
$bookTitle=trim($_POST['bookTitle']);
$bookAuthor=trim($_POST['bookAuthor']);
$category=trim($_POST['category']);
if(isset($bookTitle))
$condition="booktitle=$bookTitle";
if(isset($bookAuthor))
$condition="bookAuthor=$bookAuthor";
if(isset($category))
$condition="category=$category";
并在SQl中使用此$ condition变量。使用mysqli_real_escape_string()。 希望它能帮助你:))
答案 1 :(得分:0)
最好在开头跳过所有测试,然后简单地动态构建查询,只在设置了post变量时设置where
条件。但是如果你想保持这个逻辑(这不是太好),只需用空字符串替换你的NULL
值,这应该可以解决问题......