How can PHP be used to search for a specific string in a database with related terms?
To search for a specific string in a database with related terms using PHP, you can use SQL queries with the LIKE operator to match the string with similar terms. You can also use wildcards such as '%' to search for partial matches. By constructing a SQL query dynamically based on the search term provided by the user, you can retrieve relevant results from the database.
<?php
// Connect to 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
$searchTerm = $_GET['searchTerm'];
// Construct SQL query with LIKE operator
$sql = "SELECT * FROM table_name WHERE column_name LIKE '%$searchTerm%'";
// Execute query
$result = $conn->query($sql);
// Display results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();
?>
Related Questions
- In what situations should individuals seek assistance from colleagues or experts for PHP scripts involving external connections like Teamspeak servers?
- How can PHP beginners improve their skills and knowledge in web development?
- What are the potential risks and consequences of not securely managing passwords in PHP scripts and databases?