php-mysql count()查询重复结果

时间:2019-03-28 15:24:23

标签: php mysql

在php中使用count()查询将导致结果显示在循环中。如何解决这个问题?

phpmyadmin可以很好地显示总和,但不能将其应用于php代码。

$conn = mysqli_connect('localhost','root','','db'); 
if (!$conn) { die('db error'); };
$result = mysqli_query($conn, '
select count(*) as x from users
');

$row = mysqli_fetch_assoc($result);
echo $row['x'];

预期结果:

2 

实际输出:

2222222222222222222222222222222222222222222222222222222222222222222...

1 个答案:

答案 0 :(得分:-1)

我建议您使用prepared statements

$conn = new mysqli("localhost", "root", "", "db");
if($stmt = $conn->prepare("SELECT count(*) as x FROM users")) {
    $stmt->execute(); 
    $result = $stmt->get_result();
    while($row = $result->fetch_assoc()) {
        $number = $row['x'];
    }
    $stmt->close();
}else{
    echo "Error";
}
$conn->close();
if(isset($number)){
    echo $number;
}