Skip to content
PHP Logo

How can one track the number of SQL queries made during a page load in PHP?

To track the number of SQL queries made during a page load in PHP, you can utilize a global counter variable that increments every time a SQL query is executed. This can be achieved by creating a custom function to execute SQL queries and increment the counter within it. By monitoring this counter, you can keep track of the number of SQL queries made during a page load.

php
// Initialize a global counter variable to track the number of SQL queries
$queryCounter = 0;

// Custom function to execute SQL queries and increment the counter
function executeQuery($sql) {
    global $queryCounter;
    
    $queryCounter++; // Increment the counter
    // Execute the SQL query using your database connection
    // Add your database connection code here
    
    // Example: mysqli_query($conn, $sql);
}

// Example of executing SQL queries
executeQuery("SELECT * FROM users");
executeQuery("INSERT INTO products (name, price) VALUES ('Product A', 10.99)");

// Output the total number of SQL queries made during the page load
echo "Total SQL queries executed: " . $queryCounter;