Php 模型中的Yii计数记录
在我的web应用程序中,我想打印特定条件的记录数。但是我得到的输出是0,尽管有许多匹配条件的记录。 此代码位于另一个模型的视图中。“$data”属于该模型 我实现的代码Php 模型中的Yii计数记录,php,sql,yii,Php,Sql,Yii,在我的web应用程序中,我想打印特定条件的记录数。但是我得到的输出是0,尽管有许多匹配条件的记录。 此代码位于另一个模型的视图中。“$data”属于该模型 我实现的代码 $temp=CHtml::encode($data->name); $find=ConsumerRequest::model()->findAllByAttributes(array('requested_vegetable'=>$temp)); $count = count(
$temp=CHtml::encode($data->name);
$find=ConsumerRequest::model()->findAllByAttributes(array('requested_vegetable'=>$temp));
$count = count($find);
echo $count;
如何解决此问题?您可以尝试以下方法:
$temp=CHtml::encode($data->name);
$count = ConsumerRequest::model()->findAll(array("condition"=>"requested_vegetable = '$temp'"));
$count = count($find);
echo $count;
或
我不会使用
findAll()
函数,因为这会提取每行的所有数据。只需使用count()
或countByAttributes()
函数即可。我猜你的问题可能是这一行:
$temp=CHtml::encode($data->name);
很可能您没有将其存储在HTML编码的数据库中。试着这样做:
$count = ConsumerRequest::model()->countByAttributes(array('requested_vegetable'=>$data->name));
您也可以这样做:
$query='SELECT COUNT(id.tbl)FROM tbl'代码>
CMIIW尝试在类语法之后添加公共$count
。并使用CDbCriteria进行自定义查询。为什么在将内容输入数据库之前要对其进行HTML编码?我不知道这是否是问题所在,但这绝对是你做错了什么的迹象。另外,请使用countByAttributes
而不是findAllByAttributes
。尝试删除并仅回显tats不起作用。即使countByAttributes不会对输出进行任何更改,为什么不绑定$temp
,而是直接将其注入sql语句。另外,使用FindAll()
您正在提取所有数据,这是非常低效的,只需使用count()
我发现了代码中的错误,它只是比较整数值。而不是字符串值。有没有办法比较字符串属性…?应该可以。或者像@Pitchen所说的那样开始使用countByAttributes
。
$count = ConsumerRequest::model()->countByAttributes(array('requested_vegetable'=>$data->name));