How Can I Create Multiple Search Fields With Single Query PHP HTML

As a web developer, you might have come across a scenario where you need to provide the ability to search for different information using multiple search fields on a single page.

In this tutorial, we’ll take a look at how to achieve this by creating multiple search fields with a single query in PHP and HTML.


The Benefits of a Single Query

By using a single query, you can save time and resources compared to running multiple queries for each search field.

Additionally, it will also allow you to easily manage the search results as all of them will be stored in a single variable, making it easier to manipulate and display.

Step by Step Guide

HTML Form

Create a form in HTML where users can input the information they want to search for.

This form should include a submit button and multiple search fields, each with a unique name attribute.

<form action="search.php" method="post">
  <input type="text" name="search1" placeholder="Search Field 1">
  <input type="text" name="search2" placeholder="Search Field 2">
  <input type="submit" name="submit" value="Search">
</form>

PHP Script

Next, create a PHP script that will process the form data and execute the query.

To do this, use the $_POST array to retrieve the values entered in the form fields.

<?php
  if(isset($_POST['submit'])) {
    $search1 = $_POST['search1'];
    $search2 = $_POST['search2'];
    
    $query = "SELECT * FROM table_name WHERE field1 LIKE '%%$search1%%' OR field2 LIKE '%%$search2%%'";
    $result = mysqli_query($connection, $query);
    
    if(mysqli_num_rows($result) > 0) {
      while($row = mysqli_fetch_assoc($result)) {
        echo $row['field1'] . " " . $row['field2'];
      }
    } else {
      echo "No results found.";
    }
  }
?>

In the above code, you need to replace “table_name” with the name of the table you’re searching and “field1” and “field2” with the names of the columns you want to search.

Displaying the Results

Finally, to display the results, you can use a loop in PHP to iterate through each row of the results and display the relevant information.

<?php while($row = mysqli_fetch_assoc($result)): ?>
  <p><?php echo $row['field1'] . " " . $row['field2']; ?></p>
<?php endwhile; ?>

Conclusion

By creating multiple search fields with a single query in PHP and HTML, you can save time and resources, as well as make it easier to manage and display the search results.

With this tutorial, you should now be able to implement this functionality in your own projects.