使用fetchColumn显示记录计数


Displaying record count with fetchColumn

我正在尝试检查数据库中select的大小。我有一个表estado,我想检查这个表是否有记录"to",如果这个表有这个记录,如果没有返回0,则返回1。为此,我尝试使用fetchColumn(),但总是返回0。我不明白为什么,因为我的表有这个记录,所以它应该返回1。

我该怎么做?

public function isEstadoExist($estado){
        $stm = $this->conexao->prepare("SELECT * FROM estado t1 WHERE t1.estado = ?");
        $stm->bindParam(1, $estado);
        $existe = $stm->fetchColumn();
        echo $existe; //always display 0
    }

作为@Fred-ii-say,您必须调用$stm->execute,然后我修改SQL。

 public function isEstadoExist($estado){
            $stm = $this->conexao->prepare("SELECT count(*) as cant FROM estado t1 WHERE t1.estado = ?");
            $stm->bindParam(1, $estado);
            $stm->execute();
            $existe = $stm->fetchColumn();
            echo $existe;
    }

试试这个

public function isEstadoExist($estado){
    $query = sprintf("SELECT * FROM estado t1 WHERE t1.estado = %s", filter_var($estado, FILTER_SANITIZE_STRING));
    # Be careful the value of the column "estado" might have different case than that of "$estado"
    $stm = $this->conexao->select($query);
   return ($stm->rowCount()== 1) ? 1 : 0;
   # I prefer "return ($stm->rowCount()) ? true : false;"
}

如果您只想检查记录是否存在,则不需要绑定或从PDO语句中提取。