通过php代码对sql数据库进行多次搜索

时间:2018-10-09 11:26:56

标签: php mysql

我有一些代码可以搜索电影数据库。我需要搜索标题,流派,年份,评级等。如果一次只搜索其中之一,这很好,另一个要求是能够一次搜索多个搜索。例如,体裁+评分,会产生特定于该搜索的结果。

我的问题是我想不出如何有效地对其进行编码。任何帮助都会很棒。

<?php
$connection = mysqli_connect("localhost", "root", "", "movies");

if(!$connection){
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("Host information: %s\n", mysqli_get_host_info($connection));

/*$file = "MoviesCSV.csv";
$file_open = fopen($file,"r");
while(($csv = fgetcsv($file_open, 1000000, ",")) !== false)
{
    $title = $csv[0];
    $studio = $csv[1];
    $status = $csv[2];
    $sound = $csv[3];
    $version = $csv[4];
    $retPrice = $csv[5];
    $rating = $csv[6];
    $year = $csv[7];
    $genre = $csv[8];
    $aspect = $csv[9];

    $sql = "INSERT INTO movies
            (Title, Studio, Status, Sound, Versions, RecRetPrice, Rating, Year, Genre, Aspect)
            values 
            ('$title', '$studio', '$status', '$sound', '$version', '$retPrice', '$rating', '$year', '$genre', '$aspect')";

        if(mysqli_query($connection, $sql) === true) {
            echo("Successfully inserted into database. <br/>\n");
        }else{
            printf(mysqli_error($connection));
        }

}*/
//mysqli_close($connection);
?>

<form action="test.php" method="post">
    Title: <input type="text" name="title"/><br/>
    Genre: <input type="text" name="genre"/><br/>
    Rating: <input type="text" name="rating"/><br/>
    Year: <input type="text" name="year"/><br/>
    <p><input type="submit" value="click to submit"/></p>
</form>

<?php
  if(isset($_POST['submit'])){
    $fields = array('title', 'genre', 'rating', 'year');
      $conditions = array();
      foreach($fields as $field){
        if(isset($_POST[$field]) && $_POST[$field] != ''){
          $conditions[] = "'$field' LIKE '%" . mysqli_real_escape_string($connection, $_POST[$field]) . "%'";
      }

  }

  $query = "SELECT Title, Studio, Status, Sound, Versions, RecRetPrice, Rating, Year, Genre, Aspect FROM movies";

  if(count($conditions) > 0){
    $query .= " WHERE " . implode (' AND ', $conditions);
  }

  $result = mysqli_query($connection, $query) or die(mysql_error());
  mysqli_close($mysqli_link);

  if(isset($_POST['submit'])){
    while($row = mysqli_fetch_assoc($result)){
        $title = $row['Title'];
        $studio = $row['Studio'];
        $status = $row['Status'];
        $sound = $row['Sound'];
        $version = $row['Versions'];
        $retPrice = $row['RecRetPrice'];
        $rating = $row['Rating'];
        $year = $row['Year'];
        $genre = $row['Genre'];
        $aspect = $row['Aspect'];

        echo "Title: $title<br>Studio: $studio<br>";
      }
    }
  }
?>

我相信我对以前的帖子的修改是正确的。但是我无法打印任何内容。

0 个答案:

没有答案