来自多个文本输入的SQL查询

时间:2013-03-21 23:58:00

标签: php sql mysqli

我正在尝试从四个单独的文本字段中收集信息,并在后端生成查询以显示结果。我已经尝试了很多已在此处提出的解决方案,但我不断获得重复的结果。 我让它使用一个查询:

<?php    
$query = "SELECT * FROM book WHERE booktitle LIKE '%" . mysql_real_escape_string($_POST['title']) . "%'";
$result = mysqli_query($con, $query) or die("Error in query");
while ($row = mysqli_fetch_array($result)) {
?>
<img src="<?php echo $row[12]; ?>" width="112px" height="150px" />
<?php
echo "<b>Title: </b>" . $row[1] . "<br />";
echo "<b>Author: </b>" . $row[2] . "<br />";
echo "<b>Price:</b> &pound;" . $row[9] . "<br />";
echo "<b>Description:</b> " . substr($row[3],0,320) . "...<br /><hr>";
}

但我还需要以某种方式结合其他3的结果?

$query = "SELECT * FROM book WHERE author LIKE '%" . mysql_real_escape_string($_POST['author']) . "%'";
$query = "SELECT * FROM book WHERE isbn LIKE '%" . mysql_real_escape_string($_POST['isbn']) . "%'";
$query = "SELECT * FROM book WHERE description LIKE '%" . mysql_real_escape_string($_POST['keyword']) . "%'";

非常感谢任何帮助。提前谢谢。

2 个答案:

答案 0 :(得分:0)

<?php
$mysqli = new mysqli("localhost", "username", "password", "database_name");

$book_title = mysql_real_escape_string($_POST['title']);
$author = mysql_real_escape_string($_POST['author']);
$isbn = mysql_real_escape_string($_POST['isbn']);
$keyword = mysql_real_escape_string($_POST['keyword']);

$query = "SELECT * FROM book WHERE booktitle LIKE '%{$book_title}' OR author LIKE'%" .     $author . "%'
OR isbn LIKE '%" . $isbn . "%' OR description LIKE '%" . $keyword . "%'";
$result = $mysqli->query($query);

 while($row = $result->fetch_array()):?>
<img src="<?=$row['image_column_name']; ?>" width="112px" height="150px" />
    <b>Title:</b> <?=$row['title_column_name']; ?> <br>
    <b>Author:</b> <?=$row['author_column_name']; ?> <br>
    <b>Price:</b> <?=$row['price_column_name']; ?> <br>
    <b>Description:</b> <?=substr($row['desc_column_name'],0,320)?>
<hr>
<?php endwhile; ?>

答案 1 :(得分:0)

您可以使用带有LIKE关键字的OR语句同时搜索所有这些。

$query = "SELECT * FROM book WHERE booktitle LIKE '%" . $title . "%' OR author LIKE'%" . $author . "%' OR isbn LIKE '%" . $isbn . "%' OR description LIKE '%" . $keyword . "%';

如果变量为空,那么您将拥有WHERE booktitle LIKE '%%',它将返回所有行。您需要根据输入构建查询。

// Determine the WHEREs to use
$where = array();
if ( ! empty($title))
    $where[] = "booktitle LIKE '%" . $title . "%'";
if ( ! empty($author))
    $where[] = "author LIKE '%" . $author . "%'";
if ( ! empty($isbn))
    $where[] = "isbn LIKE '%" . $isbn . "%'";
if ( ! empty($description))
    $where[] = "description LIKE '%" . $description . "%'";

// Build the query
$query = 'SELECT * FROM book';
if ( ! empty($where))
    $query .= ' WHERE ' . implode(' OR ', $where);

注意:为了便于阅读,我省略了转义输入。