How can you optimize PHP code for reading and outputting data from a MySQL database efficiently?
To optimize PHP code for reading and outputting data from a MySQL database efficiently, you can use prepared statements to prevent SQL injection, limit the number of columns retrieved, and fetch data in batches rather than all at once to reduce memory usage.
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$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 prepared statements
$stmt = $conn->prepare("SELECT column1, column2 FROM table_name WHERE condition = ?");
$stmt->bind_param("s", $condition);
$condition = "value";
$stmt->execute();
$result = $stmt->get_result();
// Fetch and output data in batches
while ($row = $result->fetch_assoc()) {
echo $row['column1'] . " - " . $row['column2'] . "<br>";
}
// Close the connection
$stmt->close();
$conn->close();
Keywords
Related Questions
- How can the register_globals setting impact the security of a PHP application?
- What are the advantages and disadvantages of using DateTime objects in PHP for tracking building upgrade times in a browser game?
- How can PHP developers implement an API to allow external websites to access and display content without compromising security?