Search

Assuming you have a table named products in your MySQL database and you want to search for products by name. The products table has columns id, name, description, and price.

Here's the SQL query to search for products by name:

SELECT * FROM products WHERE name LIKE '%search_term%';

Where search_term is the term you want to search for. The % signs are used as wildcards to match any characters before or after the search term.

Here's a sample PHP search page that shows the search results


<form method="GET" action="search.php">
  <input type="text" name="query" placeholder="Search...">
  <button type="submit">Search</button>
</form>

This form uses the HTTP GET method to submit the search query to a PHP script named search.php. The user's input is captured in a text input field with the name query. When the user submits the form, the PHP script can access the search query using the $_GET superglobal array.

<?php
// Get the search query from the form submission
$query = $_GET['query'];

// Connect to the database
$host = 'localhost';
$user = 'yourusername';
$pass = 'yourpassword';
$dbname = 'yourdatabasename';
$conn = new mysqli($host, $user, $pass, $dbname);

// Build the SQL query
$sql = "SELECT * FROM products WHERE name LIKE '%$query%'";

// Execute the query
$result = $conn->query($sql);

// Display the search results
if ($result->num_rows > 0) {
  while ($row = $result->fetch_assoc()) {
    echo "<h2>" . $row['name'] . "</h2>";
    echo "<p>" . $row['description'] . "</p>";
    echo "<p>$" . $row['price'] . "</p>";
    echo "<hr>";
  }
} else {
  echo "No results found for '$query'";
}

// Close the database connection
$conn->close();
?>
php

This script retrieves the search query from the form submission using the $_GET superglobal, then builds and executes a SQL query that searches for products whose names match the query using the LIKE operator. The results are displayed in the same way as before.

Last updated