Jani Mani
Jani Mani

Reputation: 27

CDbCommand failed to execute the SQL statement: CDbCommand failed to prepare the SQL statement

I am using Yii with PHP and with Sql Server 2008 R2. Can anyone tell me where is the problem ?

public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Hold']))
        {
            $model->attributes=$_POST['Hold'];
            $model->startTimeHour=cc("select code from Lookup where name='$model->startTime' and type='starttime'")->queryScalar();
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }

Model $model->startTime Holds values in Dropdown. Here is the code of that as well.

<div class="control-group">
        <label class="control-label"><?php echo $form->labelEx($model,'startTime'); ?></label>
        <div class="controls">
            <?php echo $form->dropDownList($model,'startTime',$this->_startTime); ?>
            <span class="help-inline"><?php echo $form->error($model,'startTime'); ?></span>
        </div>
    </div>

Error on this Line of actionUpdate($id)

$model->startTimeHour=cc("select code from Lookup where name='$model->startTime' and type='starttime'")->queryScalar();

Error message:

CDbCommand failed to execute the SQL statement: CDbCommand failed to prepare the SQL statement

Upvotes: 2

Views: 631

Answers (2)

Jani Mani
Jani Mani

Reputation: 27

Thanks Everyone for Reply. My Problem has been solved...

Just i change line

$model->startTimeHour=cc("select code from Lookup where name='$model->startTime' and type='starttime'")->queryScalar();

to

$model->startTimeHour=date('H',strtotime($model->startTime));

Upvotes: 0

Alexander Emelianov
Alexander Emelianov

Reputation: 588

cc("") Question: is your useful alias?

function cc($sql){ return Yii::app()->db->createCommand($sql); }

I recommend you do not using user input for SQL creation. With validation in the CActiveRecord or without. Binding params is best practice for SQL preparation. This feature allows you do not think about SQL injections and parameters escaping.

Shortly, replace

cc("select code from Lookup where name='$model->startTime' and type='starttime'")->queryScalar();

to

cc("select code from Lookup where name = :name and type = 'starttime'")->bindValues([':name' => $model->startTime])->queryScalar();

But for exact answer i need see the "create statement" for your table Lookup.

Upvotes: 1

Related Questions