PHP PDO retrieve MYSQL DB Size

2020-05-05 17:22发布

问题:

Trying to convert my ugly mysql_ into PDO but I'm having difficulty creating the equivalent.

$rows = mysql_query("SHOW TABLE STATUS"); 
$dbSize = 0; 
while ($row = mysql_fetch_array($rows)) { 
$dbSize += $row['Data_length'] + $row['Index_length']; 
} 
$decimals = 2;  
$mbytes = round($dbSize/(1024*1024),$decimals);
echo "$dbSize";

I've done the following without success:

$sth = $conn->query('SHOW TABLE STATUS');
$dbSize = 0; 
$dbSize = $sth->fetch(PDO::FETCH_ASSOC)["Data_length"];
$decimals = 2;  
$mbytes = round($dbSize/(1024*1024),$decimals);
echo "$dbSize";

This also wouldn't account for the $Row["Index_length"]

This ended up working for me:

$sth = $conn->query("SHOW TABLE STATUS");
$dbSize = 0;
$Result = $sth->fetchAll();
 foreach ($Result as $Row){
  $dbSize += $Row["Data_length"] + $Row["Index_length"];  
  }
$decimals = 2;  
$mbytes = round($dbSize/(1024*1024),$decimals);
echo "$dbSize";

回答1:

Older versions of PHP does not allow dereferencing returned arrays. See example 7 on this page. To fix, try this:

$sth = $conn->query('SHOW TABLE STATUS');
$dbSize = 0;
$row = $sth->fetch(PDO::FETCH_ASSOC);
$dbSize = $row["Data_length"];
$decimals = 2;  
$mbytes = round($dbSize/(1024*1024),$decimals);
echo "$dbSize";


标签: php pdo