Are there any best practices for handling database queries and data retrieval in PHP scripts?
When handling database queries and data retrieval in PHP scripts, it is important to use prepared statements to prevent SQL injection attacks and ensure data security. Additionally, it is recommended to separate database connection logic into a separate file for reusability and maintainability.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Use prepared statements for database queries
$stmt = $conn->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row['id'] . " Name: " . $row['name'] . "<br>";
}
$stmt->close();
$conn->close();
Related Questions
- Is it advisable to prioritize code readability over micro-optimizations when working with PHP frameworks like Zend?
- What are common reasons for PHP not displaying error messages as expected?
- What are some best practices for filling an HTML template with PHP variables, considering the need to format HTML code for PHP functionality?