Bad request to the database in Yii?
I need to select from the database values on such a request "select * from prem_message where to_id 12 and del_to 0"? I writed this query but it is incorrect, please correct it by writing:
$criteria = new CDbCriteria();
// Select a fields from the database
$criteria->select='id';
$criteria->select='from_id';
$criteria->select='to_id';
$criteria->select='msg';
$criteria->select='is_read';
$criteria->select='from_del';
$criteria->select='to_del';
$criteria->select='date';
// Where to_id == current user id and not delete
$criteria->condition='to_id=:to';
$criteria->addCondition('to_del=:del','AND');
$criteria->params=array(':to'=>Yii::app()->user->id);
$criteria->params=array(':del'=> 0 );
$model = Message::model()->findAll($criteria);
Error:
CDbException
CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens. The SQL statement executed was: SELECT date FROM prem_message
t
WHERE (to_id=:to) AND (to_del=:del)
It should be rewritten as:
$criteria = new CDbCriteria();
// Select a fields from the database
$criteria->select='id, from_id, to_id, msg, is_read, from_del, to_del, date';
// Where to_id == current user id and not delete
$criteria->condition='to_id=:to';
$criteria->addCondition('to_del=:del','AND');
$criteria->params=array(':to'=>Yii::app()->user->id, ':del'=> 0 );
$model = Message::model()->findAll($criteria);
It is because if you assign variable few times - new value overrides all previous one.
You rewrite params. This must fix your error:
$criteria = new CDbCriteria();
// Select a fields from the database
$criteria->select='id';
$criteria->select='from_id';
$criteria->select='to_id';
$criteria->select='msg';
$criteria->select='is_read';
$criteria->select='from_del';
$criteria->select='to_del';
$criteria->select='date';
// Where to_id == current user id and not delete
$criteria->condition='to_id=:to';
$criteria->addCondition('to_del=:del','AND');
$criteria->params=array(
':to'=>Yii::app()->user->id),
':del'=> 0
);
$model = Message::model()->findAll($criteria);
链接地址: http://www.djcxy.com/p/60856.html
下一篇: Yii中的数据库请求不好?