Skip to content
Advertisement

Cannot terminate or close a PDO connection MySQL

The page seems to continue loading indefinitely event when the script reaches the end. How can I terminate the connection after breaking out of the PHP loop? I have set the $pdo and $usearch variables to null and reviewed other questions.

<?php
            
$pdo = new PDO("mysql:host=localhost;dbname=dbname", 'user', 'pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$sql = "SELECT `counter` FROM `table` WHERE `country` LIKE 'United States'";

$start = microtime(true);

$uresult = $pdo->query($sql);
if ($uresult) {
while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {

$elapsed = microtime(true) - $start; 

if ($elapsed > 3){
    echo "took more than 3 seconds";
    break;
}
}
}

echo "done";
$uresult = null;
$pdo=null;
?>

Advertisement

Answer

I moved to MySQLi:

$mysqli  = new mysqli("localhost", "", "", "");
$uresult = $mysqli->query($sql, MYSQLI_USE_RESULT);  
$start = microtime(true);

if ($uresult) {
while ($row = $uresult->fetch_assoc()) {
$num++;
echo $num;
$elapsed = microtime(true) - $start;    
if ($elapsed  > 20){ 
echo "More than 20 seconds";    
break;    
}
}
}

$mysqli->close();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement