获取PHP中的COUNT(*)值

时间:2014-07-02 15:23:23

标签: php mysql

我使用以下来计算表格中的行数:

// Count rows
$sql = "SELECT COUNT(*) FROM articles";
$result = mysqli_query($con,$sql);
$max = mysqli_fetch_row($result);

echo $max;

这回应array。我理解为什么,但我无法在这种情况下找到如何获得价值。我试过了$max[0]。在这种情况下,我不太了解如何引用数组中的列。

2 个答案:

答案 0 :(得分:2)

试试这个:

    $sql = "SELECT COUNT(*) as counts FROM articles";
    $result = mysqli_query($con,$sql);
    $max = mysqli_fetch_assoc($result);

    echo $max['counts'];

some docs here

编辑:

    $sql = "SELECT COUNT(*) as counts FROM articles";
    $result = mysqli_query($con,$sql);
    while($max = mysqli_fetch_assoc($result))
    {
    echo $max['counts'];
    }

答案 1 :(得分:0)

您应该使用MySQL PDO。

试试这个:

try{
    $conn = new PDO("mysql:host=localhost;dbname=dbname", username, password); 
    $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch(PDOException $e) {
        $errors = "There is no connection to the Server: localhost"; 
    }

$qry = $conn -> prepare("SELECT COUNT(*) AS counts FROM articles");

$qry -> execute();


while($row = $qry->fetch(PDO::FETCH_ASSOC)) {

   $Total = $row['counts']; 

} 
echo $Total;