PHP PDO Data_length always returns “0”

2019-03-04 08:47发布

问题:

Well, I'm just trying the following for around two hours now and I can't get it to work. The following code will always return "0". Please, can anyone see where is the problem. This should work as a charm. And in PhpMyAdmin, when I run the statement it works correctly.

Actually, this is a copy/pasted code from another question here on SO which was accepted as a working answer. Check it out here.

EDIT: No errors are thrown using: error_reporting(-1); and PDO::ERRMODE_EXCEPTION.

UPDATE: Definitely, I'm getting only the first row from the query where the Data_lenght is "0". I've tested also fetchAll, and also trying to access the Data_length index while fetching. No luck.

<!DOCTYPE html>
<head>
<title></title>
</head>
<body>

<?php
try {
    error_reporting(-1);
    $host_name  = "my_hsot";
    $database   = "my_db";
    $user_name  = "my_user";
    $password   = "my_pwd";
    $conn = new PDO("mysql:host=$host_name;dbname=$database", $user_name, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $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 . "\n" . $row["Data_length"];
    } catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
?>
</body>
</html>

Any help is appreciated.

回答1:

PDO always returns "0" because $row = $sth->fetch(PDO::FETCH_ASSOC); returns only the first row from the query, and the index of Data_length there is "0", as it could be any other value.