0

I want to execute a query in a view page in Yii, here is my code:

$connection=Yii::app()->db;
$connection->active=true;
$sql = "insert into news(idNews, news, display) values('', 'anything', 0)";
$command=$connection->createCommand($sql);
$command->execute();

but nothing is happened, what is the error with my code?

3
  • I don't know YII, but from the first look createCommand returns a normal PDO. So at first you need check if $command->execute() true, if not you have check what error mysql reports. Commented Jun 21, 2014 at 18:26
  • if idNews is auto incremental, you don't have to pass anything about it, also check /runtime/application.log if an error happend and you missed it Commented Jun 22, 2014 at 3:58
  • Using data management requests such as inserts goes against the practice of separating views, business logic and data management, which is used in MVC frameworks such as Yii. If you have to do this, you should re-evaluate your need to use a framework such as Yii. Commented Jun 22, 2014 at 8:48

3 Answers 3

5

Or:

$sql = 'insert into news (news, display) values (:news, :display)';
$parameters = array(':user_id'=>'', ':created' => date('Y-m-d H:i:s'));
Yii::app()->db->createCommand($sql)->execute($parameters);
Sign up to request clarification or add additional context in comments.

Comments

3

Why do you execute a query in a view page?In the data access layer is the place you usually do it from. You can try first in the controller.

Here you can read about Data Access Objects in Yii: http://www.yiiframework.com/doc/guide/1.1/en/database.dao

Comments

0

Try this:

$news = new News();
$news->news = "anything";
$news->display = 0;
$news->save(false);

6 Comments

@user3194430 do you have News model?
I posted one more answer, try that and let me know
ohh, I forgot to mention that the php file that contian this code is not in the protected dir
i know, but I putted it outside the protected dir, because thers is an ajax function need to use the file
I am not sure bro) Why dont you do your ajax functions in controller?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.