2

I have this MySQL insert:

INSERT INTO restaurant (id_restaurant, id_category)
SELECT id_rest, id_cat
FROM restaurant_menu rm, category_menu cm
WHERE rm.name = "discount" AND cm.name = "beach";

but now I want to do this insert in Yii. I know that I can do it using Yii query builder, but I think that if the query/insert/delete/update is very long, that is too complex. Therefore, I would like to know if is possible to use MySQL code into a Yii code directly, I mean, for example something similar to this:

$sql='INSERT INTO restaurant (id_restaurant, id_category) SELECT id_rest, id_cat FROM restaurant_menu rm, category_menu cm WHERE rm.name = "discount" AND cm.name = "beach"'

$command=$connection->createCommand($sql);

Please, someone could show me how to do this insert using the MySQL code directly in Yii?

2
  • Careful with your quoting in your second example. If you're using " for your string, use ' for your data. Or better, use placeholder values. Commented Nov 14, 2013 at 21:55
  • Thanks @user2989514. I have just corrected the code. Am I using right the "" and '' now? Commented Nov 14, 2013 at 23:02

1 Answer 1

1

You basically have it right:

$connection = Yii::app()->db;
$command=$connection->createCommand($sqlStatement);
$command->execute();

http://www.yiiframework.com/doc/api/1.1/CDbConnection

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Pitchinnate. I understand that $sqlStatement in my case is $sql, is it right?
Yes the name of the variable is arbitrary it could be anything.

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.