Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii: php -> Cannot execute SQL command in SiteController

Tags:

sql

php

mysql

yii

yii2

I have some problem when submitting the _form.php to SiteController.php this error message will appear,

"CDbCommand failed to execute the SQL statement: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; "

It cannot run the query. Also try with another query command, the error is same.

SiteController.php

public function actionCreate()
{
    $model = new Detail;
   if (isset($_POST['Detail'])) {
       // print_r($_POST['Detail']);
        $model->attributes = $_POST['Detail'];
        $connection = Yii::app()->db;

        $data = date('Y-m-d');
        $date = "'" . $data . "'";
        $teach_id = Yii::app()->user->getId();

        $i = 1;
        foreach ($_POST['Detail'] as $stud=>$status) 
        {
            $sql = 'INSERT INTO {{detail}} (`id`, `student_id`, `teacher_id`, `date`, `status`) VALUES 
                    (NULL, ' . $stud . ',' . $teach_id . ',' . $date . ', ' . $i . ' );';


            $command = $connection->createCommand($sql);
            $exec = $command->query();
        } 
        if ($exec) {
            $this->redirect(array('index'));
        }
    }
    $this->render('create', array('model' => $model, ));
}
like image 860
mrdidie Avatar asked May 19 '26 14:05

mrdidie


1 Answers

Try to replace {{detail}} with real table name and use double quotes for whole string and single quote for each variable

"INSERT INTO {{detail}}
    (`id`, `student_id`, `teacher_id`, `date`, `status`)
VALUES
    (NULL, '$stud', '$teach_id', '$date', '$i');"

replace

$date = "'" . $data . "'";

to

$date = $data;

and you are using the same key of $_POST array in different cases

$model->attributes = $_POST['Detail'];
...
foreach ($_POST['Detail'] as $stud => $status)