To check the execution time of a query in PHP, you can use the PHP’s built-in microtime()
function. This function returns the current Unix timestamp with microseconds, which can be used to measure the time taken to execute a query. Here’s an example of how to do it:
// Start the timer
$startTime = microtime(true);
// Your database connection and query execution code here
// For example:
$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";
// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Example query
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);
// End the timer
$endTime = microtime(true);
// Calculate the execution time
$executionTime = $endTime - $startTime;
// Output the result
echo "Query executed in: " . $executionTime . " seconds";
// Close the database connection
$conn->close();
Make sure to replace the placeholder values (your_servername
, your_username
, your_password
, your_dbname
, your_table
) with your actual database credentials and query.
The $executionTime
variable will hold the time taken to execute the query in seconds (including microseconds). Keep in mind that the execution time can vary depending on factors like server load and database complexity. Therefore, it’s essential to consider this when analyzing query performance.