What are some best practices for handling database connections and queries in PHP scripts like the one provided?
When handling database connections and queries in PHP scripts, it is important to properly establish and close connections to avoid potential memory leaks and performance issues. One best practice is to use prepared statements to prevent SQL injection attacks and improve query performance. Additionally, consider implementing error handling to gracefully manage any database connection or query errors that may occur.
// 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 a query using a prepared statement
$stmt = $conn->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
// Process the query result
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$stmt->close();
$conn->close();
Related Questions
- What are common pitfalls when using if statements in PHP for conditional logic?
- What are the advantages and disadvantages of using getter/setter methods instead of func_get_args() in a PHP session management system?
- What are the advantages and disadvantages of splitting database entries in PHP versus using a single column with multiple values?