What are the best practices for handling database queries and error checking in PHP scripts?
When handling database queries in PHP scripts, it is important to properly sanitize input data to prevent SQL injection attacks. Additionally, always use prepared statements to execute queries safely and efficiently. Error checking should be implemented to handle potential database connection issues, query errors, and other exceptions that may arise during the execution of the script.
// Example of handling database queries and error checking in PHP scripts
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check for connection errors
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare and execute a query using a prepared statement
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
// Handle query results
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Process query results
}
} else {
echo "No results found";
}
// Close the database connection
$stmt->close();
$conn->close();
Related Questions
- What are some best practices to follow when including content from external pages in PHP to maintain the integrity of the original content?
- What are the differences between the mysql_query() and mysqli_query() functions in PHP?
- What are some best practices for securely passing data from a PHP form to a forum editor?