How can the output of SQL query results be optimized and automated in PHP scripts?

To optimize and automate the output of SQL query results in PHP scripts, you can use a combination of prepared statements, fetching data in chunks, and using a loop to iterate over the results. This approach helps reduce memory usage and improve performance when dealing with large datasets.

// Connect to the database
$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 the SQL query
$stmt = $conn->prepare("SELECT * FROM table_name");
$stmt->execute();

// Bind the result set to variables
$stmt->bind_result($column1, $column2, $column3);

// Fetch and output the results in chunks
while ($stmt->fetch()) {
    echo "Column 1: " . $column1 . " | Column 2: " . $column2 . " | Column 3: " . $column3 . "<br>";
}

// Close the statement and connection
$stmt->close();
$conn->close();