Please, I am totally new to Yii1.1, I am following a video tutorial and I have benn trying to follow up closely. I am trying to create and update the album model as indicated in the video tutorial. I typed everything the presenter typed: my codes are given below:
The AlbumController
class AlbumController extends Controller
{
/**
* @var string the default layout for the views. Defaults to ‘//layouts/column2’, meaning
* using two-column layout. See ‘protected/views/layouts/column2.php’.
*/
public $layout=’//layouts/column2′;
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Album;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Album']))
{
$model->attributes=$_POST['Album'];
if($model->save()){
//$this->redirect(array('view','id'=>$model->id));
Yii::app()->user->setFlash('saved', 'Data saved!');
$this->redirect(array('update','id'=>$model->id));
}
else{
Yii::app()->user->setFlash('failure', 'Data not saved!');
}
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Album']))
{
$model->attributes=$_POST['Album'];
if($model->save()){
//$this->redirect(array('view','id'=>$model->id));
Yii::app()->user->setFlash('saved', "Data saved!");
$this->redirect(array('update','id'=>$model->id));
}else{
Yii::app()->user->setFlash('failure', "Data not saved!");
}
}
$this->render('update',array(
'model'=>$model,
));
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
}
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Album');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Album('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Album']))
$model->attributes=$_GET['Album'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer $id the ID of the model to be loaded
* @return Album the loaded model
* @throws CHttpException
*/
public function loadModel($id)
{
$model=Album::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param Album $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='album-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
The Album model class
/**
* This is the model class for table «tbl_album».
*
* The followings are the available columns in table ‘tbl_album’:
* @property integer $id
* @property string $name
* @property string $tags
* @property integer $owner_id
* @property integer $shareable
* @property string $created_dt
*
* The followings are the available model relations:
* @property User $owner
* @property Photo[] $photos
*/
class Album extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return ‘tbl_album’;
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('owner_id, shareable, category_id', 'numerical', 'integerOnly'=>true),
array('name, tags', 'length', 'max'=>255),
array('description', 'length', 'max'=>1024),
array('description', 'match', 'pattern'=>'/[w]+/u'),// -_' ,p{L}0-!
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, name, tags, owner_id, shareable, created_dt', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
//defined function beforeSave()..
protected function beforeSave(){
if(parent::beforeSave()){
if($this->isNewRecord){
$this->created_dt = new CDbExpression("NOW()");
$this->owner_id = Yii::app()->user->id;
}
return true;
}else
return false;
}
public function scopes(){
return array(
'shareable'=>array(
'order'=>'created_dt DESC',
'condition'=>'shareable=1',
)
);
}
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),
'photos' => array(self::HAS_MANY, 'Photo', 'album_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'name' => 'Name',
'tags' => 'Tags',
'owner_id' => 'Owner',
'category_id'=>'Category',
'description'=>'Description',
'shareable' => 'Shareable',
'created_dt' => 'Created Dt',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('name',$this->name,true);
$criteria->compare('tags',$this->tags,true);
$criteria->compare('description',$this->description);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Album the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
The Photo Model Class
/**
* This is the model class for table «tbl_photo».
*
* The followings are the available columns in table ‘tbl_photo’:
* @property integer $id
* @property integer $album_id
* @property string $filename
* @property string $caption
* @property string $alt_text
* @property string $tags
* @property integer $sort_order
* @property string $created_dt
* @property string $lastupdate_dt
*
* The followings are the available model relations:
* @property Comment[] $comments
* @property Album $album
*/
class Photo extends CActiveRecord
{
private $_uploads;
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'tbl_photo';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('album_id, sort_order', 'numerical', 'integerOnly'=>true),
array('filename', 'length', 'max'=>500),
array('tags', 'length', 'max'=>256),
array('caption, alt_text, created_dt, lastupdate_dt', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, album_id, filename, caption, alt_text, tags, sort_order, created_dt, lastupdate_dt', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'comments' => array(self::HAS_MANY, 'Comment', 'photo_id'),
'album' => array(self::BELONGS_TO, 'Album', 'album_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'album_id' => 'Album',
'filename' => 'Filename',
'caption' => 'Caption',
'alt_text' => 'Alt Text',
'tags' => 'Tags',
'sort_order' => 'Sort Order',
'created_dt' => 'Created Dt',
'lastupdate_dt' => 'Lastupdate Dt',
);
}
public function getImageParam(){
if(empty($this->_uploads)){
$this->_uploads = Yii::app()->params['uploads']. "/";
return $this->_uploads;
}
}
public function getUrl(){
return $this->getImageParam()."uploads/".CHtml::encode($this->filename);
}
public function getThumb(){
return $this->getImageParam()."thumbs/".CHtml::encode($this->filename);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('album_id',$this->album_id);
$criteria->compare('filename',$this->filename,true);
$criteria->compare('caption',$this->caption,true);
$criteria->compare('alt_text',$this->alt_text,true);
$criteria->compare('tags',$this->tags,true);
$criteria->compare('sort_order',$this->sort_order);
$criteria->compare('created_dt',$this->created_dt,true);
$criteria->compare('lastupdate_dt',$this->lastupdate_dt,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Photo the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
The Photo Model
/**
* This is the model class for table «tbl_photo».
*
* The followings are the available columns in table ‘tbl_photo’:
* @property integer $id
* @property integer $album_id
* @property string $filename
* @property string $caption
* @property string $alt_text
* @property string $tags
* @property integer $sort_order
* @property string $created_dt
* @property string $lastupdate_dt
*
* The followings are the available model relations:
* @property Comment[] $comments
* @property Album $album
*/
class Photo extends CActiveRecord
{
private $_uploads;
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'tbl_photo';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('album_id, sort_order', 'numerical', 'integerOnly'=>true),
array('filename', 'length', 'max'=>500),
array('tags', 'length', 'max'=>256),
array('caption, alt_text, created_dt, lastupdate_dt', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, album_id, filename, caption, alt_text, tags, sort_order, created_dt, lastupdate_dt', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'comments' => array(self::HAS_MANY, 'Comment', 'photo_id'),
'album' => array(self::BELONGS_TO, 'Album', 'album_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'album_id' => 'Album',
'filename' => 'Filename',
'caption' => 'Caption',
'alt_text' => 'Alt Text',
'tags' => 'Tags',
'sort_order' => 'Sort Order',
'created_dt' => 'Created Dt',
'lastupdate_dt' => 'Lastupdate Dt',
);
}
public function getImageParam(){
if(empty($this->_uploads)){
$this->_uploads = Yii::app()->params['uploads']. "/";
return $this->_uploads;
}
}
public function getUrl(){
return $this->getImageParam()."uploads/".CHtml::encode($this->filename);
}
public function getThumb(){
return $this->getImageParam()."thumbs/".CHtml::encode($this->filename);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('album_id',$this->album_id);
$criteria->compare('filename',$this->filename,true);
$criteria->compare('caption',$this->caption,true);
$criteria->compare('alt_text',$this->alt_text,true);
$criteria->compare('tags',$this->tags,true);
$criteria->compare('sort_order',$this->sort_order);
$criteria->compare('created_dt',$this->created_dt,true);
$criteria->compare('lastupdate_dt',$this->lastupdate_dt,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Photo the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
I am getting this error: CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (school2go2.tbl_album, CONSTRAINTtbl_album_ibfk_1FOREIGN KEY (owner_id) REFERENCEStbl_user(id) ON DELETE NO ACTION ON UPDATE NO ACTION). The SQL statement executed was: INSERT INTOtbl_album(name,tags,description,shareable,created_dt,owner_id) VALUES (:yp0, :yp1, :yp2, :yp3, NOW(), :yp4)
Please I am totally new to yii and even StackOverflow, pardon my inappropriate editing.I am still learning.
Please, I am totally new to Yii1.1, I am following a video tutorial and I have benn trying to follow up closely. I am trying to create and update the album model as indicated in the video tutorial. I typed everything the presenter typed: my codes are given below:
The AlbumController
class AlbumController extends Controller
{
/**
* @var string the default layout for the views. Defaults to ‘//layouts/column2’, meaning
* using two-column layout. See ‘protected/views/layouts/column2.php’.
*/
public $layout=’//layouts/column2′;
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Album;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Album']))
{
$model->attributes=$_POST['Album'];
if($model->save()){
//$this->redirect(array('view','id'=>$model->id));
Yii::app()->user->setFlash('saved', 'Data saved!');
$this->redirect(array('update','id'=>$model->id));
}
else{
Yii::app()->user->setFlash('failure', 'Data not saved!');
}
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Album']))
{
$model->attributes=$_POST['Album'];
if($model->save()){
//$this->redirect(array('view','id'=>$model->id));
Yii::app()->user->setFlash('saved', "Data saved!");
$this->redirect(array('update','id'=>$model->id));
}else{
Yii::app()->user->setFlash('failure', "Data not saved!");
}
}
$this->render('update',array(
'model'=>$model,
));
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
}
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Album');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Album('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Album']))
$model->attributes=$_GET['Album'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer $id the ID of the model to be loaded
* @return Album the loaded model
* @throws CHttpException
*/
public function loadModel($id)
{
$model=Album::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param Album $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='album-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
The Album model class
/**
* This is the model class for table «tbl_album».
*
* The followings are the available columns in table ‘tbl_album’:
* @property integer $id
* @property string $name
* @property string $tags
* @property integer $owner_id
* @property integer $shareable
* @property string $created_dt
*
* The followings are the available model relations:
* @property User $owner
* @property Photo[] $photos
*/
class Album extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return ‘tbl_album’;
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('owner_id, shareable, category_id', 'numerical', 'integerOnly'=>true),
array('name, tags', 'length', 'max'=>255),
array('description', 'length', 'max'=>1024),
array('description', 'match', 'pattern'=>'/[w]+/u'),// -_' ,p{L}0-!
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, name, tags, owner_id, shareable, created_dt', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
//defined function beforeSave()..
protected function beforeSave(){
if(parent::beforeSave()){
if($this->isNewRecord){
$this->created_dt = new CDbExpression("NOW()");
$this->owner_id = Yii::app()->user->id;
}
return true;
}else
return false;
}
public function scopes(){
return array(
'shareable'=>array(
'order'=>'created_dt DESC',
'condition'=>'shareable=1',
)
);
}
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),
'photos' => array(self::HAS_MANY, 'Photo', 'album_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'name' => 'Name',
'tags' => 'Tags',
'owner_id' => 'Owner',
'category_id'=>'Category',
'description'=>'Description',
'shareable' => 'Shareable',
'created_dt' => 'Created Dt',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('name',$this->name,true);
$criteria->compare('tags',$this->tags,true);
$criteria->compare('description',$this->description);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Album the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
The Photo Model Class
/**
* This is the model class for table «tbl_photo».
*
* The followings are the available columns in table ‘tbl_photo’:
* @property integer $id
* @property integer $album_id
* @property string $filename
* @property string $caption
* @property string $alt_text
* @property string $tags
* @property integer $sort_order
* @property string $created_dt
* @property string $lastupdate_dt
*
* The followings are the available model relations:
* @property Comment[] $comments
* @property Album $album
*/
class Photo extends CActiveRecord
{
private $_uploads;
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'tbl_photo';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('album_id, sort_order', 'numerical', 'integerOnly'=>true),
array('filename', 'length', 'max'=>500),
array('tags', 'length', 'max'=>256),
array('caption, alt_text, created_dt, lastupdate_dt', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, album_id, filename, caption, alt_text, tags, sort_order, created_dt, lastupdate_dt', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'comments' => array(self::HAS_MANY, 'Comment', 'photo_id'),
'album' => array(self::BELONGS_TO, 'Album', 'album_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'album_id' => 'Album',
'filename' => 'Filename',
'caption' => 'Caption',
'alt_text' => 'Alt Text',
'tags' => 'Tags',
'sort_order' => 'Sort Order',
'created_dt' => 'Created Dt',
'lastupdate_dt' => 'Lastupdate Dt',
);
}
public function getImageParam(){
if(empty($this->_uploads)){
$this->_uploads = Yii::app()->params['uploads']. "/";
return $this->_uploads;
}
}
public function getUrl(){
return $this->getImageParam()."uploads/".CHtml::encode($this->filename);
}
public function getThumb(){
return $this->getImageParam()."thumbs/".CHtml::encode($this->filename);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('album_id',$this->album_id);
$criteria->compare('filename',$this->filename,true);
$criteria->compare('caption',$this->caption,true);
$criteria->compare('alt_text',$this->alt_text,true);
$criteria->compare('tags',$this->tags,true);
$criteria->compare('sort_order',$this->sort_order);
$criteria->compare('created_dt',$this->created_dt,true);
$criteria->compare('lastupdate_dt',$this->lastupdate_dt,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Photo the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
The Photo Model
/**
* This is the model class for table «tbl_photo».
*
* The followings are the available columns in table ‘tbl_photo’:
* @property integer $id
* @property integer $album_id
* @property string $filename
* @property string $caption
* @property string $alt_text
* @property string $tags
* @property integer $sort_order
* @property string $created_dt
* @property string $lastupdate_dt
*
* The followings are the available model relations:
* @property Comment[] $comments
* @property Album $album
*/
class Photo extends CActiveRecord
{
private $_uploads;
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'tbl_photo';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('album_id, sort_order', 'numerical', 'integerOnly'=>true),
array('filename', 'length', 'max'=>500),
array('tags', 'length', 'max'=>256),
array('caption, alt_text, created_dt, lastupdate_dt', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, album_id, filename, caption, alt_text, tags, sort_order, created_dt, lastupdate_dt', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'comments' => array(self::HAS_MANY, 'Comment', 'photo_id'),
'album' => array(self::BELONGS_TO, 'Album', 'album_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'album_id' => 'Album',
'filename' => 'Filename',
'caption' => 'Caption',
'alt_text' => 'Alt Text',
'tags' => 'Tags',
'sort_order' => 'Sort Order',
'created_dt' => 'Created Dt',
'lastupdate_dt' => 'Lastupdate Dt',
);
}
public function getImageParam(){
if(empty($this->_uploads)){
$this->_uploads = Yii::app()->params['uploads']. "/";
return $this->_uploads;
}
}
public function getUrl(){
return $this->getImageParam()."uploads/".CHtml::encode($this->filename);
}
public function getThumb(){
return $this->getImageParam()."thumbs/".CHtml::encode($this->filename);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('album_id',$this->album_id);
$criteria->compare('filename',$this->filename,true);
$criteria->compare('caption',$this->caption,true);
$criteria->compare('alt_text',$this->alt_text,true);
$criteria->compare('tags',$this->tags,true);
$criteria->compare('sort_order',$this->sort_order);
$criteria->compare('created_dt',$this->created_dt,true);
$criteria->compare('lastupdate_dt',$this->lastupdate_dt,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Photo the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
I am getting this error: CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (school2go2.tbl_album, CONSTRAINTtbl_album_ibfk_1FOREIGN KEY (owner_id) REFERENCEStbl_user(id) ON DELETE NO ACTION ON UPDATE NO ACTION). The SQL statement executed was: INSERT INTOtbl_album(name,tags,description,shareable,created_dt,owner_id) VALUES (:yp0, :yp1, :yp2, :yp3, NOW(), :yp4)
Please I am totally new to yii and even StackOverflow, pardon my inappropriate editing.I am still learning.
Обновлено
Ускорьте свой компьютер сегодня с помощью этой простой загрузки. г.
Если у вас возникла ошибка с кодами ошибок cdbException на этом компьютере, вам следует проверить эти методы восстановления.
<этот стиль равен «width: 288px;» scope = «col»> ИМЯ
ОПИСАНИЕ
| CDBException :: m_nRetCode | Содержит открытую базу данных Conn. .. |
| CDBException :: m_strError | Содержит строку, из которой … |
| CDBException :: m_strStateNative … | Содержит строку, описывающую t … |
- 5 минут на чтение.
Синтаксис
Класс
: общедоступное исключение CE
Участники
Общедоступные элементы
Тип содержит два общедоступных элемента данных, которые любой сможет использовать для определения причины упущения или для вывода сообщения печати, описывающего одно исключение. CDBException – это материал, созданный поверх того, что создается функциями-членами, которые ссылаются на группы базы данных.
Исключения – это периодические выполнения, которые содержат условия USB, убивающие программу, например ошибки источника маркетинговой информации или сетевого ввода-вывода. Ошибки, которые можно ожидать увидеть при выполнении известной программы, обычно не являются исключением.
Вы получаете эти объекты в массиве выражения CATCH. Вы также можете сгенерировать объекты CDBException из своего собственного значения с помощью глобальной функции AfxThrowDBException .
Дополнительно Для получения информации об обработке исключений в целом или об объектах CDBException см. Обработка исключений (MFC) вместе с Исключениями: Исключения базы данных .
Иерархия наследования
Требования
CdbException :: M_nretcode
Содержит код ошибки RETCODE ODBC, возвращаемый функцией API ODBC (интерфейс прикладного программирования).
Этот тип по существу включает коды с префиксом SQL через определенные коды ODBC и коды с префиксом AFX_SQL через определенные классы базы данных. Для CDBException он по отдельности содержит одно из общепринятых значений:
-
Драйвер AFX_SQL_ERROR_API_CONFORMANCE как
CDatabase :: OpenExпомимо запроса профессионаловCDatabase :: Openне обнаруживает ожидаемой цели совместимости ODBC API 1 (SQL_OAC_LEVEL1). -
Обновлено
Вы устали от того, что ваш компьютер работает медленно? Раздражают разочаровывающие сообщения об ошибках? ASR Pro — это решение для вас! Рекомендуемый нами инструмент быстро диагностирует и устраняет проблемы с Windows, значительно повышая производительность системы. Так что не ждите больше, скачайте ASR Pro сегодня!

AFX_SQL_ERROR_CONNECT_FAIL Ошибка при подключении к жесткому диску. Вы передали NULL
CDatabaseдля ссылки на конструктор Recordset вашей компании, но не смогли предпринять попытку пересылки на основе соединенияGetDefaultConnect.>
-
AFX_SQL_ERROR_DATA_TRUNCATED Вы запросили много данных, чем получили предоставленное пространство. Информацию о растущем количестве ошибок в хранилище данных для ваших типов документов
CStringилиCByteArrayможно найти в инструкцииnMaxLengthдля RFX_Text и RFX_Binary в разделе “Макросы” и просто глобальные переменные. -
AFX_SQL_ERROR_DYNASET_NOT_SUPPORTED Не удалось вызвать
CRecordset :: Openдля запроса хорошей динамической программы. Динсеты поддерживаются не только авиатором. -
AFX_SQL_ERROR_EMPTY_COLUMN_LIST Вы пытались создать конкретную входную таблицу (или то, что вы указали, определенно может быть идентифицировано как вызов процедуры и / или, возможно, оператор SELECT), но содержимое не было идентифицировано при обмене полями записи (RFX ), Вызывает ваш заголовок
DoFieldExchange. -
AFX_SQL_ERROR_FIELD_SCHEMA_MISMATCH Широкий спектр функций RFX рядом с
DoFieldExchangeПолная замена не соответствует типу данных строки вокруг набора записей. -
AFX_SQL_ERROR_ILLEGAL_MODE Вы прошли
CRecordset :: Updateбез предварительного взаимодействия сCRecordset :: AddNewс помощьюCRecordset :: Edit, чтобы имеют. -
AFX_SQL_ERROR_LOCK_MODE_NOT_SUPPORTED Ваш запрос блокировки записи не может быть современным, потому что ваш драйвер ODBC не поддерживает блокировку. Вы
-
afx_sql_error_multiple_rows_affected с помощью обнаружения
CRecordset :: UpdateилиDeleteдля таблицы без уникального ключа, а также изменения некоторых других записи. -
AFX_SQL_ERROR_NO_CURRENT_RECORD Вы пытались изменить или удалить ранее удаленную запись. Вы должны перейти к новой активной записи после нескольких удалений.
-
AFX_SQL_ERROR_NO_POSITIONED_UPDATES Ваш запрос динамического набора не может быть удовлетворен, поскольку драйвер ODBC не поддерживает позиционированные обновления.
-
AFX_SQL_ERROR_NO_ROWS_AFFECTED Вы отметили
CRecordset :: Updateилиdelete, когда метод был запущен, запись данных не может быть найдена. -
AFX_SQL_ERROR_ODBC_LOAD_FAILED Попытка загрузить ODBC. DLL Windows не может найти эту DLL или даже загрузить ее. Эту ошибку можно считать фатальной.
-
AFX_SQL_ERROR_ODBC_V2_REQUIRED Ваш запрос, предоставленный Dynaset, может завершиться ошибкой, поскольку требуется сертифицированный драйвер ODBC уровня 2.
-
AFX_SQL_ERROR_RECORDSET_FORWARD_ONLY Попытка поиска не удалась, поскольку форма данных завершена и не поддерживает прокрутку назад.
-
AFX_SQL_ERROR_SNAPSHOT_NOT_SUPPORTED Электронная почта для
CRecordset :: Openс запросом моментального снимка failedsa. Драйвер не поддерживает фото. (Это следует делать только в том случае, если библиотека курсоров ODBC ODBCCURS.DLL недоступна.) -
AFX_SQL_ERROR_SQL_CONFORMANCE Велосипедист, вызывающий
CDatabase :: OpenExилиCDatabase :: Open, не соответствует требуемому «минимальному» уровню соответствия ODBC SQL. “(SQL_OSC_MINIMUM). -
AFX_SQL_ERROR_SQL_NO_TOTAL ODBC racer не смог указать числовой размер, относящийся к значению данных
CLongBinary. Вероятно, процесс завершился неудачно, потому что блок глобальной памяти вполне может быть не выделен заранее. -
AFX_SQL_ERROR_RECORDSET_READONLY Покупатель пытается обновить набор записей, доступный только для чтения, или, возможно, первичный источник данных доступен только для чтения. При использовании предоставленного объекта
CDatabaseнебольшие операции обновления могут выполняться с каким-то набором записей. -
Ошибка функции SQL_ERROR. Личное сообщение об ошибке, возвращаемое функцией ODBC
SQLError, сохраняется в результатахm_strError. Функция -
Ошибка sql_invalid_handle просто из-за недопустимого дескриптора среды, недопустимой службы подключения, согласно инструкциям. Это указывает на неисправность канала. Нет других доступных файлов, кроме функции ODBC
SQLError.
Коды, обычно определяемые ODBC, с префиксом SQL. Коды с префиксом AFX можно определить в AFXDB.H, который выбран в MFC INCLUDE.
CDBException :: M_strError
Строка описывает ошибку с помощью буквенно-цифровых слов и предложений. См. m_strStateNativeOrigin , предназначенный для получения более подробной информации и ситуации.
CDBException :: M_strStateNativeOrigin
Строка полностью означает «Состояние:% s, Источник:% ld, Источник:% s», в форматах коды последовательно заменяются повышениями, которые, в частности, описывают:
-
SQLSTATE, абсолютная строка с завершающим нулем, содержащая огромный 5-значный код ошибки, когда она возвращается в параметре szSqlState, связанном с помощью функции ODBC
SQLError. Результаты SQLSTATE перечислены в Приложении A, Коды ошибок ODBC , в Справочнике по программированию ODBC. Пример: «S0022». -
Пользовательский код ошибки, по которому источник данных был возвращен в параметре pfNativeError
SQLError, дает хорошие результаты. Пример: 207. -
Сообщение об ошибке отправлено обратно параметру функции szErrorMsg
SQLError. Это сообщение состоит из нескольких имен в скобках. Поскольку реальная ошибка передается от источника к пользователю, один компонент ODBC (источник данных, командная строка, менеджер владельцев автомобилей) добавляет свое собственное имя. Эта информация помогает человеку определить источник ошибки. Пример: [Microsoft] [Драйвер ODBC SQL Server] [SQL Framework Server]
интерпретирует строку ошибки, а также помещает наши компоненты в m_strStateNativeOrigin ; Хотя m_strStateNativeOrigin содержит информацию о нескольких ошибках, ошибки, несомненно, разделяются переносами строки. Платформа вставляет этот буквенно-цифровой текст ошибки в m_strError .
Дополнительные сведения о кодах исключительных ситуаций, реализованных для создания этой строки, см. в наиболее связанной функции SQLError в Справочнике по программированию ODBC.
Пример
Из ODBC: «Статус: S0022, Собственный: 207, Источник: [Microsoft] [Драйвер ODBC SQL] [SQL Server] Недопустимое имя столбца« ColName »»
См. также
Этот курс предназначен для получения учебной программы MFC Open Database Connectivity (ODBC). Если вместо этого вы используете новые классы объектов доступа к данным (DAO), используйте исключение Take CDaoException . Все имена классов DAO в настоящее время имеют префикс “CDao”. Дополнительную информацию см. В материале Обзор: Программирование баз данных .
Ускорьте свой компьютер сегодня с помощью этой простой загрузки. г.
What Are CdbException Error Codes And How To Fix Them?
Wat Zijn CdbException-foutcodes En Hoe Kunnen Ze Worden Opgelost?
Que Sont Les Codes D’erreur CdbException Et Comment Les Corriger ?
Cosa Sono I Codici Di Errore CdbException E Come Risolverli?
Was Sind CdbException-Fehlercodes Und Wie Können Sie Behoben Werden?
CdbException 오류 코드는 무엇이며 어떻게 수정합니까?
O Que São Códigos De Erro CdbException E Como Corrigi-los?
Vad är CdbException -felkoder Och Hur åtgärdas De?
¿Qué Son Los Códigos De Error CdbException Y Cómo Solucionarlos?
Co To Są Kody Błędów CdbException I Jak Je Naprawić?
г.

I made a table called «Customer» and I want to make a simple Yii application of create and view. Here’s the piece of my code in CustomerController.php:
class CustomerController extends Controller
{
public $layout = '//layouts/column2';
public function actionCreate()
{
$model = new Customer();
$this->redirect(array('view', 'id' => $model->id));
$this->render('create', array(
'model' => $model,
));
}
public function actionView()
{
$model = new Customer();
$result = $model->viewCustomer();
foreach ($result as $row) {
echo $row["title"];
echo $row["fname"];
echo $row["lname"];
echo $row["addressline"];
echo $row["town"];
echo $row["zipcode"];
echo $row["phone"];
}
$this->render('view', array(
'model' => $this->$model(),
));
}
}
and here’s the code in my model named Customer.php
public function createCustomer()
{
$connection = Yii::app()->db;
$sql = "INSERT INTO Customer (title,fname,lname,addressline,town,zipcode,phone)VALUES(:title,:fname,:lname,:addressline,:town,:zipcode,:phone)";
$command = $connection->createCommand($sql);
$command->bindParam(":title", $title, PDO::PARAM_STR);
$command->bindParam(":fname", $fname, PDO::PARAM_STR);
$command->bindParam(":lname", $lname, PDO::PARAM_STR);
$command->bindParam(":addressline", $addressline, PDO::PARAM_STR);
$command->bindParam(":town", $town, PDO::PARAM_STR);
$command->bindParam(":zipcode", $zipcode, PDO::PARAM_STR);
$command->bindParam(":phone", $phone, PDO::PARAM_STR);
$result = $command->execute();
if ($result == 1) {
return "ok";
}
public function viewCustomer()
{
$connection = Yii::app()->db;
$sql = "Select * from Customer";
$dataReader = $connection->createCommand($sql)->query();
$dataReader->bindColumn(1, $title);
$dataReader->bindColumn(2, $fname);
$dataReader->bindColumn(3, $lname);
$dataReader->bindColumn(4, $addressline);
$dataReader->bindColumn(5, $town);
$dataReader->bindColumn(6, $zipcode);
$dataReader->bindColumn(7, $phone);
$result = $dataReader->queryAll();
return $result;
}
}
But, I always having this kind of error:
CDbException
CDbCommand failed to execute the SQL statement: CDbCommand failed to prepare the SQL statement: SQLSTATE[HY000]: General error: 1 no such table: Customer. The SQL statement executed was: Select * from Customer.
My friend said that I don’t have a get value. How can I resolve this? Please help me guys. Thank you in advance. BTW, I’m using PDO.
| description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Learn more about: CDBException Class |
CDBException Class |
11/04/2016 |
|
|
eb9e1119-89f5-49a7-b9d4-b91cee1ccc82 |
Represents an exception condition arising from the database classes.
Syntax
class CDBException : public CException
Members
Public Data Members
| Name | Description |
|---|---|
| CDBException::m_nRetCode | Contains an Open Database Connectivity (ODBC) return code, of type RETCODE. |
| CDBException::m_strError | Contains a string that describes the error in alphanumeric terms. |
| CDBException::m_strStateNativeOrigin | Contains a string describing the error in terms of the error codes returned by ODBC. |
Remarks
The class includes two public data members you can use to determine the cause of the exception or to display a text message describing the exception. CDBException objects are constructed and thrown by member functions of the database classes.
[!NOTE]
This class is one of MFC’s Open Database Connectivity (ODBC) classes. If you are instead using the newer Data Access Objects (DAO) classes, use CDaoException instead. All DAO class names have «CDao» as a prefix. For more information, see the article Overview: Database Programming.
Exceptions are cases of abnormal execution involving conditions outside the program’s control, such as data source or network I/O errors. Errors that you might expect to see in the normal course of executing your program are usually not considered exceptions.
You can access these objects within the scope of a CATCH expression. You can also throw CDBException objects from your own code with the AfxThrowDBException global function.
For more information about exception handling in general, or about CDBException objects, see the articles Exception Handling (MFC) and Exceptions: Database Exceptions.
Inheritance Hierarchy
CObject
CException
CDBException
Requirements
Header: afxdb.h
CDBException::m_nRetCode
Contains an ODBC error code of type RETCODE returned by an ODBC application programming interface (API) function.
Remarks
This type includes SQL-prefixed codes defined by ODBC and AFX_SQL-prefixed codes defined by the database classes. For a CDBException, this member will contain one of the following values:
-
AFX_SQL_ERROR_API_CONFORMANCE The driver for a
CDatabase::OpenExorCDatabase::Opencall does not conform to required ODBC API Conformance level 1 ( SQL_OAC_LEVEL1). -
AFX_SQL_ERROR_CONNECT_FAIL Connection to the data source failed. You passed a NULL
CDatabasepointer to your recordset constructor and the subsequent attempt to create a connection based onGetDefaultConnectfailed. -
AFX_SQL_ERROR_DATA_TRUNCATED You requested more data than you have provided storage for. For information on increasing the provided data storage for
CStringorCByteArraydata types, see thenMaxLengthargument for RFX_Text and RFX_Binary under «Macros and Globals.» -
AFX_SQL_ERROR_DYNASET_NOT_SUPPORTED A call to
CRecordset::Openrequesting a dynaset failed. Dynasets are not supported by the driver. -
AFX_SQL_ERROR_EMPTY_COLUMN_LIST You attempted to open a table (or what you gave could not be identified as a procedure call or SELECT statement) but there are no columns identified in record field exchange (RFX) function calls in your
DoFieldExchangeoverride. -
AFX_SQL_ERROR_FIELD_SCHEMA_MISMATCH The type of an RFX function in your
DoFieldExchangeoverride is not compatible with the column data type in the recordset. -
AFX_SQL_ERROR_ILLEGAL_MODE You called
CRecordset::Updatewithout previously callingCRecordset::AddNeworCRecordset::Edit. -
AFX_SQL_ERROR_LOCK_MODE_NOT_SUPPORTED Your request to lock records for update could not be fulfilled because your ODBC driver does not support locking.
-
AFX_SQL_ERROR_MULTIPLE_ROWS_AFFECTED You called
CRecordset::UpdateorDeletefor a table with no unique key and changed multiple records. -
AFX_SQL_ERROR_NO_CURRENT_RECORD You attempted to edit or delete a previously deleted record. You must scroll to a new current record after a deletion.
-
AFX_SQL_ERROR_NO_POSITIONED_UPDATES Your request for a dynaset could not be fulfilled because your ODBC driver does not support positioned updates.
-
AFX_SQL_ERROR_NO_ROWS_AFFECTED You called
CRecordset::UpdateorDelete, but when the operation began the record could no longer be found. -
AFX_SQL_ERROR_ODBC_LOAD_FAILED An attempt to load the ODBC.DLL failed; Windows could not find or could not load this DLL. This error is fatal.
-
AFX_SQL_ERROR_ODBC_V2_REQUIRED Your request for a dynaset could not be fulfilled because a Level 2-compliant ODBC driver is required.
-
AFX_SQL_ERROR_RECORDSET_FORWARD_ONLY An attempt to scroll did not succeed because the data source does not support backward scrolling.
-
AFX_SQL_ERROR_SNAPSHOT_NOT_SUPPORTED A call to
CRecordset::Openrequesting a snapshot failed. Snapshots are not supported by the driver. (This should only occur when the ODBC cursor library ODBCCURS.DLL is not present.) -
AFX_SQL_ERROR_SQL_CONFORMANCE The driver for a
CDatabase::OpenExorCDatabase::Opencall does not conform to the required ODBC SQL Conformance level of «Minimum» (SQL_OSC_MINIMUM). -
AFX_SQL_ERROR_SQL_NO_TOTAL The ODBC driver was unable to specify the total size of a
CLongBinarydata value. The operation probably failed because a global memory block could not be preallocated. -
AFX_SQL_ERROR_RECORDSET_READONLY You attempted to update a read-only recordset, or the data source is read-only. No update operations can be performed with the recordset or the
CDatabaseobject it is associated with. -
SQL_ERROR Function failed. The error message returned by the ODBC function
SQLErroris stored in them_strErrordata member. -
SQL_INVALID_HANDLE Function failed due to an invalid environment handle, connection handle, or statement handle. This indicates a programming error. No additional information is available from the ODBC function
SQLError.
The SQL-prefixed codes are defined by ODBC. The AFX-prefixed codes are defined in AFXDB.H, found in MFCINCLUDE.
CDBException::m_strError
Contains a string describing the error that caused the exception.
Remarks
The string describes the error in alphanumeric terms. For more detailed information and an example, see m_strStateNativeOrigin.
CDBException::m_strStateNativeOrigin
Contains a string describing the error that caused the exception.
Remarks
The string is of the form «State:%s,Native:%ld,Origin:%s», where the format codes, in order, are replaced by values that describe:
-
The SQLSTATE, a null-terminated string containing a five-character error code returned in the szSqlState parameter of the ODBC function
SQLError. SQLSTATE values are listed in Appendix A, ODBC Error Codes, in the ODBC Programmer’s Reference. Example: «S0022». -
The native error code, specific to the data source, returned in the pfNativeError parameter of the
SQLErrorfunction. Example: 207. -
The error message text returned in the szErrorMsg parameter of the
SQLErrorfunction. This message consists of several bracketed names. As an error is passed from its source to the user, each ODBC component (data source, driver, Driver Manager) appends its own name. This information helps to pinpoint the origin of the error. Example: [Microsoft][ODBC SQL Server Driver][SQL Server]
The framework interprets the error string and puts its components into m_strStateNativeOrigin; if m_strStateNativeOrigin contains information for more than one error, the errors are separated by newlines. The framework puts the alphanumeric error text into m_strError.
For additional information about the codes used to make up this string, see the SQLError function in the ODBC Programmer’s Reference.
Example
From ODBC: «State:S0022,Native:207,Origin:[Microsoft][ODBC SQL Server Driver][SQL Server] Invalid column name ‘ColName'»
In m_strStateNativeOrigin: «State:S0022,Native:207,Origin:[Microsoft][ODBC SQL Server Driver][SQL Server]»
In m_strError: «Invalid column name ‘ColName'»
See also
CException Class
Hierarchy Chart
CDatabase Class
CRecordset Class
CFieldExchange Class
CRecordset::Update
CRecordset::Delete
CException Class
Замучился воевать с такой же проблемой.
FrontEnd работает все ОК. Консоль выдает такуюже ошибку.
Гуглил, гуглил так и ненагуглил. У всех либо PDO не включен, либо забывают Yii консоль настроить. У меня вроде все сделанно но не работает.
Машинка: ubuntu LAMP
Замучился пробовать, вроде все ОК и вроде все правельно но не работает.
в /etc/php5/apache2/conf.d/ и в /etc/php5/cli/conf.d/ присутствуют pdo.ini со строчкой extension=pdo.so и pdo_mysql.ini с нужным содержанием extension=pdo_mysql.so
теоритечески нечего не мешает работать, все настроенно. А по факту ошибка.
/protected/config/main.php
Код: Выделить всё
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=wincalc',
'emulatePrepare' => true,
'username' => 'root',
'password' => '1234',
'charset' => 'utf8',
),
/protected/config/cansole.php
Код: Выделить всё
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=wincalc',
'emulatePrepare' => true,
'username' => 'root',
'password' => '1234',
'charset' => 'utf8',
phpinfo
PDO
PDO support enabled
PDO drivers mysqlpdo_mysql
PDO Driver for MySQL enabled
Client API version 5.5.34Directive Local Value Master Value
pdo_mysql.default_socket /var/run/mysqld/mysqld.sock /var/run/mysqld/mysqld.sock
На всякий случай тект ошибки
exception ‘CDbException’ with message ‘CDbConnection failed to open the DB connection: could not find driver’ in /hdd/a/skvnet/fw/db/CDbConnection.php:381
Stack trace:
#0 /hdd/a/skvnet/fw/db/CDbConnection.php(330): CDbConnection->open()
#1 /hdd/a/skvnet/fw/db/CDbConnection.php(308): CDbConnection->setActive(true)
#2 /hdd/a/skvnet/fw/base/CModule.php(387): CDbConnection->init()
#3 /hdd/a/skvnet/fw/base/CApplication.php(438): CModule->getComponent(‘db’)
#4 /hdd/a/skvnet/fw/db/ar/CActiveRecord.php(623): CApplication->getDb()
#5 /hdd/a/skvnet/fw/db/ar/CActiveRecord.php(2309): CActiveRecord->getDbConnection()
#6 /hdd/a/skvnet/fw/db/ar/CActiveRecord.php(387): CActiveRecordMetaData->__construct(Object(TablAllKlient))
#7 /hdd/a/skvnet/fa/protected/models/TablAllKlient.php(27): CActiveRecord::model(‘TablAllKlient’)
#8 /hdd/a/skvnet/fa/protected/commands/SendsmstoallcalledCommand.php(33): TablAllKlient::model()
#9 /hdd/a/skvnet/fw/console/CConsoleCommandRunner.php(67): SendsmstoallcalledCommand->run(Array)
#10 /hdd/a/skvnet/fw/console/CConsoleApplication.php(91): CConsoleCommandRunner->run(Array)
#11 /hdd/a/skvnet/fw/base/CApplication.php(169): CConsoleApplication->processRequest()
#12 /hdd/a/skvnet/fw/yiic.php(33): CApplication->run()
#13 /hdd/a/skvnet/fa/protected/yiic.php(7): require_once(‘/hdd/a/skvoznik…’)
#14 {main}root@lanket-air:/var/a/skvnet/fa/protected#
смущает результат команды в консоле php -m
а именно отсутствие pdo_mysql. Хотя по настройкам должон быть.
[PHP Modules]
Core
ctype
date
dom
ereg
fileinfo
filter
hash
iconv
json
libxml
pcre
PDO
pdo_sqlite
Phar
posix
Reflection
session
SimpleXML
SPL
SQLite
sqlite3
standard
tokenizer
xml
xmlreader
xmlwriter[Zend Modules]
Добрый день,
после обновления операционки (был переезд на новый VPS) debian 9 -> 11 и обновления mysql.
Фронтэнд полностью работает, работает отправка писем из форм, все ок.
Проблема с бэкэндом, при попытке отредактировать любой объект недвижимости в каталоге получаю ошибку
CDbException
CDbCommand не удалось исполнить SQL-запрос: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value…
Так же не могу создать любой новый объект — Добавить объявление
CDbException
CDbCommand не удалось исполнить SQL-запрос: SQLSTATE[HY000]: General error: 1364 Field ‘loc_country’ doesn’t have a default value. The SQL statement executed was: INSERT INTO `ore_apartment` (`visits`, `date_updated`, `is_price_poa`, `num_of_rooms`, `floor`, `floor_total`, `square`, `land_square`, `window_to`, `living_conditions`, `services`, `berths`, `lat`, `lng`, `rating`, `price_type`, `sorter`, `autoVKPostId`, `autoFBPostId`, `autoTwitterPostId`, `ploshchad_zh12`, `ploshchad_ku`, `obshchaja_pl`, `obshchaja_pl1`, `active`, `owner_active`, `type`, `date_manual_updated`, `description_ru`, `owner_id`, `obj_type_id`, `price`, `date_created`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7, :yp8, :yp9, :yp10, :yp11, :yp12, :yp13, :yp14, :yp15, :yp16, :yp17, :yp18, :yp19, :yp20, :yp21, :yp22, :yp23, :yp24, :yp25, :yp26, NOW(), :yp27, :yp28, :yp29, :yp30, NOW())
/framework/db/CDbCommand.php(358)
346 {
347 if($this->_connection->enableProfiling)
348 Yii::endProfile(‘system.db.CDbCommand.execute(‘.$this->getText().$par.’)’,’system.db.CDbCommand.execute’);
349
350 $errorInfo=$e instanceof PDOException ? $e->errorInfo : null;
351 $message=$e->getMessage();
352 Yii::log(Yii::t(‘yii’,’CDbCommand::execute() failed: {error}. The SQL statement executed was: {sql}.’,
353 array(‘{error}’=>$message, ‘{sql}’=>$this->getText().$par)),CLogger::LEVEL_ERROR,’system.db.CDbCommand’);
354
355 if(YII_DEBUG)
356 $message.=’. The SQL statement executed was: ‘.$this->getText().$par;
357
358 throw new CDbException(Yii::t(‘yii’,’CDbCommand failed to execute the SQL statement: {error}’,
Это касается не только Добавить объявление — но похожие ошибки и получаю при попытке добавить Новость, Вопрос-ответ, Комментарий.
Все связаны с изменениями которые произошли в новых версиях mysql и не были учтены в коде движка сайта:
https://github.com/yiisoft/yii/issues/2993
Куда рыть не знаю.
Помогите советом, готов оплатить посильную помощь.