Question

I don't know if the title is correct, anyway here is what I need:

This is my code:

$start = microtime();
$string = $_POST['string'];
$matches = $SQL->prepare("SELECT * FROM `users` WHERE `name` LIKE ?");
$matches->execute(array('%'.$string.'%'));

echo "Done in: " . round($_GLOBALS['time'], 4);
foreach($matches->fetchAll() as $match) {
    [..]
}
$end = microtime();
$time = $end - $start;

As you can see, I'm measuring the time of the query + displaying records, microtime() needs to be at the bottom of the foreach but I need to display the measured time ($time variable) before a foreach. As you can see I've tried to do this like this: echo "Done in: " . round($_GLOBALS['time'], 4); but it always is returning 0 (null).

What should I do?

Was it helpful?

Solution

You should do something like this:

$start = microtime(true);
$string = $_POST['string'];
$matches = $SQL->prepare("SELECT * FROM `users` WHERE `name` LIKE ?");
$matches->execute(array('%'.$string.'%'));

$output = '';
foreach($matches->fetchAll() as $match) {
    $output .= $someText;
    [...]
}

$end = microtime(true);
$time = $end - $start;
echo "Done in: " . round($time, 4);
echo $output;

Also, note I am using the optional parameter of true because this returns the time as a decimal number instead of two parts as the documentation states.

OTHER TIPS

afuzzyllama's answer is one way using a variable. You could also capture the foreach loop's output into a buffer, echo the time, then output from the buffer:

$start = microtime();
$string = $_POST['string'];
$matches = $SQL->prepare("SELECT * FROM `users` WHERE `name` LIKE ?");
$matches->execute(array('%'.$string.'%'));

ob_start();
foreach($matches->fetchAll() as $match) {
    [..]
}
$table = ob_get_contents();
ob_end_clean();

$end = microtime();
$time = $end - $start;
echo "Done in: " . round($GLOBALS['time'], 4);
echo $table;

Also, I don't know why you're using $GLOBALS['time'] here.

Can't you just calculate the time using microtime before the foreach too? e.g.

$start = microtime();
$string = $_POST['string'];
$matches = $SQL->prepare("SELECT * FROM `users` WHERE `name` LIKE ?");
$matches->execute(array('%'.$string.'%'));

echo "Done in: " . (microtime() - $start);
foreach($matches->fetchAll() as $match) {
    [..]
}
$end = microtime();
$time = $end - $start;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top