How can you improve the efficiency and readability of the PHP script by optimizing the way data is fetched and displayed from the database?
To improve the efficiency and readability of the PHP script, you can optimize the way data is fetched and displayed from the database by using prepared statements and separating your database logic from your presentation logic. Prepared statements help prevent SQL injection attacks and can improve performance by reusing query execution plans. Separating database logic from presentation logic makes your code easier to read and maintain.
<?php
// Database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare statement
$stmt = $pdo->prepare("SELECT name, email FROM users WHERE id = :id");
// Bind parameters
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
// Execute the query
$stmt->execute();
// Fetch data
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// Display data
echo "Name: " . $user['name'] . "<br>";
echo "Email: " . $user['email'];
?>
Keywords
Related Questions
- What are some common pitfalls in PHP coding that can lead to issues with form data submission using the POST method?
- What are some potential issues with sorting values in PHP, especially when dealing with negative and positive numbers?
- What are some alternative methods to Select2 and jQuery for enhancing user input in PHP forms with large datasets?