How can you limit the output from a database query in PHP without using a while loop?

To limit the output from a database query in PHP without using a while loop, you can utilize the fetchAll() method in combination with the FETCH_NUM or FETCH_ASSOC fetch style to retrieve all rows at once. Then, you can use array slicing to limit the number of rows returned based on your desired limit.

// Connect to database
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");

// Prepare and execute query
$stmt = $pdo->query("SELECT * FROM table");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Limit the output
$limitedResults = array_slice($results, 0, 10); // Limit to first 10 rows

// Output the limited results
foreach ($limitedResults as $row) {
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}