How can PHP be utilized to search for specific terms in a MySQL database?
To search for specific terms in a MySQL database using PHP, you can use the SELECT query with the WHERE clause to filter the results based on the search term. You can use PHP variables to store the search term input by the user and then dynamically construct the SQL query to search for that term in the database.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get search term from user input
$searchTerm = $_POST['searchTerm'];
// Construct SQL query to search for term in database
$sql = "SELECT * FROM table_name WHERE column_name LIKE '%$searchTerm%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results found";
}
$conn->close();
?>
Keywords
Related Questions
- How can hidden or non-printable characters affect PHP code execution and cause syntax errors?
- What are some best practices for determining the size of a folder in PHP for setting upload limits?
- In what ways can a PHP developer improve their code structure and readability by following recommended practices for variable naming and data manipulation functions like explode()?