What are some best practices for implementing a "Freitextsuche" (free text search) for a MySQL database using PHP?
Implementing a "Freitextsuche" (free text search) for a MySQL database using PHP involves creating a search form where users can input keywords to search for in the database. The PHP script will then query the database using the entered keywords and return relevant results.
<?php
// Establish a connection to the 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 the search query from the form
$search_query = $_POST['search_query'];
// Query the database for relevant results
$sql = "SELECT * FROM table_name WHERE column_name LIKE '%$search_query%'";
$result = $conn->query($sql);
// Display the search results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results found";
}
// Close the database connection
$conn->close();
?>
Related Questions
- What are the potential pitfalls of including templates in PHP methods and how can they be avoided?
- Are there any built-in PHP functions for formatting numbers with decimal points?
- Are there any security considerations to keep in mind when allowing users to delete lines from a text file via a PHP script?