What best practices should be followed when handling search queries in PHP to display MYSQL data in an HTML table?
When handling search queries in PHP to display MYSQL data in an HTML table, it's important to sanitize user input to prevent SQL injection attacks. Additionally, use prepared statements to securely interact with the database. Finally, properly format the retrieved data in an HTML table to ensure a clean and organized display.
<?php
// Connect 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);
}
// Sanitize user input
$search_query = mysqli_real_escape_string($conn, $_GET['search_query']);
// Prepare and execute the query
$stmt = $conn->prepare("SELECT * FROM table_name WHERE column_name LIKE ?");
$stmt->bind_param("s", $search_query);
$stmt->execute();
$result = $stmt->get_result();
// Display data in an HTML table
echo "<table>";
while ($row = $result->fetch_assoc()) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
// Close the connection
$stmt->close();
$conn->close();
?>
Keywords
Related Questions
- How can one ensure that data passed through $_GET is properly sanitized and validated in PHP?
- How can interfaces be used in PHP to enforce certain methods in classes, as discussed in the forum thread?
- How can error reporting and display be configured in PHP to troubleshoot issues like headers already sent?