What best practices should be followed when fetching and displaying data from a SQL query in a PHP script?
When fetching and displaying data from a SQL query in a PHP script, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize and validate user input before executing the query to ensure data integrity. Finally, properly handle errors and exceptions to provide a secure and reliable application.
// Establish a database connection
$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);
}
// Prepare and execute SQL query
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $columnValue);
$columnValue = $_POST['input'];
$stmt->execute();
// Fetch and display results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo "Column: " . $row['column'] . "<br>";
}
// Close statement and connection
$stmt->close();
$conn->close();
Related Questions
- What are some best practices for implementing a pause functionality in a PHP script to prevent server overload when processing multiple entries?
- What steps can be taken to troubleshoot and resolve PHP and MySQL compatibility issues on a Windows Server with IIS?
- What best practices should be followed when assigning values in a switch statement in PHP?