Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using the following code to make a connection to the database, fetch the Data_length index column, and calculate the database size based on the data.

For some reason PDO will always return "0", which is the value for the Data_length index in the first row. Whatever I do, I only get the first rows index.

The database is MySQL, the engine MyISAM.

PHP Version: 5.5.38
MySQL Version: 5.5.50

Here is the source code.

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

<?php
try {
    error_reporting(-1);
    $host_name  = "my_host";
    $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 . "
" . $row["Data_length"];
    } catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
?>
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
520 views
Welcome To Ask or Share your Answers For Others

1 Answer

Add a while loop,

while($row= $sth->fetch( PDO::FETCH_ASSOC )){ 
   echo $row['your_field_name'];
}

Or you can use fetchAll

$rows = $sth->fetchAll();
print_r($rows);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...