简体   繁体   English

PHP搜索MySQL数据库-多个搜索变量

[英]PHP Search MySQL Database - Multiple Search Variables

For all those that care, the if not empty statement worked for me 对于所有关心的人,如果不是空的话对我有用

I'm new to SQL and PHP and am trying to implement a search functionality to grab data from a MySQL database that deals with wines. 我是SQL和PHP的新手,正在尝试实现搜索功能以从处理葡萄酒的MySQL数据库中获取数据。

I have figured out how to do a query where there is one search variable, and I have figured out how to do it with two search variables, i'm sure i could continue on that pattern - but what i'd like to do is implement a search function that can search based on what the user inputs into the variables (That means, the user must enter at least one value, and the search will grab fields relevant to the search variable). 我已经找到了如何在一个搜索变量中进行查询的方法,并且已经找到了如何使用两个搜索变量进行查询的方法,我敢肯定我可以继续使用该模式- 但是我想做的是实现一种搜索功能,该功能可以根据用户输入到变量中的内容进行搜索 (这意味着用户必须输入至少一个值,并且搜索将获取与搜索变量相关的字段)。

Say for example I have these search variables: 举例来说,我有以下搜索变量:

  • wine name - (user can leave this blank or enter a value) 葡萄酒名称-(用户可以将其保留为空白或输入一个值)
  • wine type - (user enters a value) 葡萄酒类型-(用户输入一个值)
  • year - (user can leave this blank or enter a value) 年-(用户可以将此空白留空或输入一个值)

Based on how many variables the user enters will dictate how refined the search is. 用户输入多少变量将决定搜索的精确程度。

I've tried searching the forums but can't seem to find anything. 我尝试搜索论坛,但似乎找不到任何东西。 Apologies if my formatting, or question is wrong. 抱歉,如果我的格式或问题不对。 Would appreciate any help or a point in the right direction, thanks! 感谢您的帮助或朝正确方向的指点,谢谢!

Here is my code so far that works if the user enters both variables 'wineName' and 'wineryName'. 如果用户输入变量“ wineName”和“ wineryName”,到目前为止,这是我到目前为止的代码。 Tried using isset to trigger some sort of switch, but i don't think i'm on the right track. 尝试使用isset来触发某种切换,但是我认为我的方向不正确。

<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>Answer Page</title>
</head>
<body bgcolor="white">

<?php 

    function showerror() {
        die("Error " . mysql_errno() . " : " . mysql_error());
    }

    require 'db.php';

    // Show all wines in a region in a <table>
    function displayWines($connection, $query, $wineName) {
    // Run the query on the server
        if (!($result = @ mysql_query ($query, $connection))) {
            showerror();
        }

    // Find out how many rows are available
        $rowsFound = @ mysql_num_rows($result);

        // If the query has results ...
        if ($rowsFound > 0) {
            // ... print out a header
            print "You searched for $wineName with a region of $wineryName <br><br>";

            // and start a <table>.
            print "\n<table>\n<tr>" .
                "\n\t<th>Wine ID</th>" .
                "\n\t<th>Wine Name</th>" .
                "\n\t<th>Winery Name</th>" . 
                "\n\t<th>Year</th>\n</tr>"; 

            // Fetch each of the query rows
            while ($row = @ mysql_fetch_array($result)) {
            // Print one row of results
            print "\n<tr>\n\t<td>{$row["wine_id"]}</td>" .
                "\n\t<td>{$row["wine_name"]}</td>" .
                "\n\t<td>{$row["winery_name"]}</td>" .
                "\n\t<td>{$row["year"]}</td>\n</tr>"; 
            } //end while loop body

            //finish table 
            print "\n</table>"; 
        } //end if $rowsFound body 

        //Report how many rows were found
        print "<br>{$rowsFound} records found matching your criteria<br>"; 
    } //end of function

    // Connect to the MySQL server
    if (!($connection = @ mysql_connect(DB_HOST, DB_USER, DB_PW))) {
        die("Could not connect");
    }

    //get user data 
    $wineName = $_GET['wineName']; 
    $wineryName = $_GET['wineryName'];

    if (!mysql_select_db(DB_NAME, $connection)) {
        showerror();
    }

    //start a query 
    $query = "SELECT wine_id, wine_name, winery_name, year 
    FROM wine, winery 
    WHERE wine.winery_id = winery.winery_id"; 

    if (isset($wineName)) {
        $query .= " AND wine_name = '{$wineName}'";
    }

    if (isset($wineryName)) {
        $query .= " AND winery_name = '{$wineryName}'";
    }

    //order the list 
    $query .= " ORDER BY wine_name"; 

    //run query, show results 
    displayWines($connection, $query, $wineName); 

?>

</body>
</html>

First of all, change your INPUT 's names to an array, eg 首先,将INPUT的名称更改为数组,例如

<input name="wine[wineName]" ...>
<input name="wine[wineryName]" ...>

Now you have to change the way you get the user data: 现在,您必须更改获取用户数据的方式:

// Define an array of allowed fields ("whitelist")
$fields = array('wineName', 'wineryName');
// Get the fields given by the user
$wine = array();
foreach($fields as $field)
    if (isset($_GET['wine'][$field]))
        $wine[$field] = mysql_real_escape_string($_GET['wine'][$field]);

// ... your code here ...

//start a query
$query = "SELECT wine_id, wine_name, winery_name, year 
FROM wine, winery 
WHERE wine.winery_id = winery.winery_id";

foreach ($wine as $field => $value) $query .= " AND ".$field." = '".$value."'";

One important hint: NEVER use user given input in your query without escaping! 一个重要提示:切勿在转义时使用用户给定的输入! (see http://php.net/manual/en/function.mysql-real-escape-string.php ) (请参见http://php.net/manual/zh/function.mysql-real-escape-string.php

//start a query 
$query = "SELECT wine_id, wine_name, winery_name, year 
FROM wine, winery 
WHERE wine.winery_id = winery.winery_id"; 

if (isset($wineName)) {
    $query .= " AND wine_name LIKE '%$wineName%'";
}

if (isset($wineryName)) {
    $query .= " AND winery_name LIKE '%$wineryName%'";
}

//order the list 
$query .= " ORDER BY wine_name"; 

//run query, show results 
displayWines($connection, $query, $wineName); 

Please have a look at the following lines: 请看以下几行:

print "\n<tr>\n\t<td>{$row["wine_id"]}</td>" .
      "\n\t<td>{$row["wine_name"]}</td>" .
      "\n\t<td>{$row["winery_name"]}</td>" .
      "\n\t<td>{$row["year"]}</td>\n</tr>"; 

It should be 它应该是

print "\n<tr>\n\t<td>{$row['wine_id']}</td>" .
      "\n\t<td>{$row['wine_name']}</td>" .
      "\n\t<td>{$row['winery_name']}</td>" .
      "\n\t<td>{$row['year']}</td>\n</tr>"; 

instead. 代替。 Your double quotes for the array key are closing your string. 数组键的双引号将关闭字符串。

Note: 注意:

Because your tutor has said to use the deprecated mysql_* functions you can't do much about it. 因为您的导师说过要使用不建议使用的mysql_ *函数,所以您不能做太多事情。 But please bear in mind, that you better should use parameterized prepared statements and bind your input values to the parameters (with PDO or mysqli). 但是请记住,最好使用参数化的预处理语句,并将输入值绑定到参数(使用PDO或mysqli)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM