首页 > 解决方案 > 无法在 php 中正确使用 sql 查询的结果

问题描述

我想要做的是获取满足特定要求的行数,并且根据执行的数量,脚本会做不同的事情。

我的代码:

        $sql2 = "SELECT COUNT(email)FROM subscribers WHERE id= ?";
        $stmt2 = $conn->prepare($sql2);
        $stmt2->bind_param("s", $id);
        $stmt2->execute();
        $callbacks = $stmt2->get_result();
        while($rows = $callbacks->fetch_assoc()){
            $results = $rows;
        }
        $stmt2->close();

        if ($results <2001){
            $email = trim($_POST["email"]);
        }else{
            $email_err = "This user has reached the limmit to what their plan can allow .";
        }

我遇到的问题是我不确定如何实际使用行数。

在这种配置中,它不关心结果的数量,它只是发布它们。

如果我做这样id_err = $results; 的事情来查看查询结果是什么,它会给我一个数组到字符串的转换错误。

这种操作听起来像硬件密集型,如果您认为应该直接查询行并使用 PHP 计算它们,请告诉我如何。

我也尝试过$results = $rows['count']使用不同的名称(例如“total”和“result”)进行一些变体,但它们仍然会发布。当我尝试查看带有它的查询结果时,id_err = $results;它会完全忽略它并发布。

为了避免混淆 $id_err 是什么,它会在脚本被使用时停止发布。

并澄清这个 SQL 查询是在一个条件语句中。

先感谢您。

标签: phpsql

解决方案


count函数将所有记录作为一行返回,计数..因此删除while并比较适当的索引。

$sql2 = "SELECT COUNT(email) as the_count FROM subscribers WHERE id= ?";
$stmt2 = $conn->prepare($sql2);
$stmt2->bind_param("s", $id);
$stmt2->execute();
$callbacks = $stmt2->get_result();
$rows = $callbacks->fetch_assoc();
$stmt2->close();
if ($rows['the_count'] < 2001){
     $email = trim($_POST["email"]);
}else{
     $email_err = "This user has reached the limmit to what their plan can allow .";
}

推荐阅读