How can PHP be used to iterate through multiple tables in a database to perform a search operation?
To iterate through multiple tables in a database to perform a search operation in PHP, you can use a loop to dynamically construct SQL queries for each table and execute them. You can use a UNION clause to combine the results from multiple tables into a single result set.
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Search keyword
$search_keyword = "example";
// Array of tables to search
$tables = array("table1", "table2", "table3");
// Initialize an empty array to store search results
$search_results = array();
// Iterate through tables and perform search
foreach ($tables as $table) {
$sql = "SELECT * FROM $table WHERE column_name LIKE '%$search_keyword%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$search_results[] = $row;
}
}
}
// Display search results
foreach ($search_results as $result) {
// Display search results as needed
echo $result['column_name'] . "<br>";
}
// Close database connection
$conn->close();
?>
Keywords
Related Questions
- What are the potential security implications of using PHP to access network interface information?
- What are the potential pitfalls of not understanding the relationship between Unix users, file permissions, and PHP usage in WordPress installations?
- How can PHP developers optimize their code when working with multiple radio buttons in a form?