How can a beginner without PHP knowledge create a search function to display data from a MySQL database on a website?
To create a search function to display data from a MySQL database on a website, a beginner can start by creating a simple HTML form where users can input their search query. Then, using PHP, the form input can be captured and used to query the database for relevant data. The retrieved data can then be displayed on the website using HTML.
<?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);
}
// Check if form is submitted
if(isset($_POST['search'])) {
$search = $_POST['search'];
// Query database for relevant data
$sql = "SELECT * FROM table_name WHERE column_name LIKE '%$search%'";
$result = $conn->query($sql);
// Display search results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. "<br>";
echo "Email: " . $row["email"]. "<br>";
// Add more fields as needed
}
} else {
echo "No results found";
}
}
// Close database connection
$conn->close();
?>
Keywords
Related Questions
- How can input validation and sanitization be implemented in the PHP script to prevent potential SQL injection attacks when adding new records to the database?
- What are the potential pitfalls or challenges when trying to display tabular data from grouped arrays in PHP?
- How can PHP developers efficiently handle cases where there is no corresponding data for a specific key in a multidimensional array?