How can PHP be used to search results from multiple MySQL tables based on user input?
When a user inputs a search query, PHP can be used to dynamically generate a SQL query that searches multiple MySQL tables based on the user input. This can be achieved by concatenating multiple SELECT statements with UNION or JOIN clauses to combine the results from different tables. The PHP code snippet below demonstrates how to construct a SQL query that searches for a keyword in two different tables (table1 and table2) and fetches the results using MySQLi.
<?php
// User input
$search_query = $_POST['search_query'];
// MySQL connection
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
// SQL query to search in multiple tables
$sql = "SELECT * FROM table1 WHERE column_name LIKE '%$search_query%'
UNION
SELECT * FROM table2 WHERE column_name LIKE '%$search_query%'";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Output search results
echo $row['column_name'] . "<br>";
}
} else {
echo "No results found.";
}
$mysqli->close();
?>
Keywords
Related Questions
- What is the correct syntax for creating a hidden input field in PHP forms?
- How can error_reporting() function help in debugging PHP code and identifying issues like headers already sent?
- What best practices should be followed to ensure secure transmission and storage of sensitive information in PHP applications, particularly in the context of user authentication?