2

I am new to Craft CMS. Please tell me about how can I save data into database in Craft?

I have searched a lot of results about my query but nothing give advantage to me.

Thanks in advance.

2 Answers 2

4

I suggest you to read about the Yii Query Builder

craft()->db->createCommand()
    ->insert('mytablename', array(
        'field1'    => 'foo',
        'field2'    => 'bar'
    ));

Or you can use Active Records in Craft

$record = new Record();
$record->field1 = 'foo';
$record->field2 = 'bar';
$record->save();

Or you can use Craft Elements (entries/categories/tags)

$entry = new EntryModel();
$attributes = [
   'section'   => $yourSectionId,
   'entryType' => $yourEntryTypeId,
   'field1'    => 'foo',
   'field2'    => 'bar'
];
$entry->getContent()->setAttributes($attributes);
craft()->entries()->saveEntry($entry); 
2
  • Let me know if you got it Commented Feb 23, 2018 at 12:40
  • ok i will notify
    – zain
    Commented Feb 23, 2018 at 12:58
1

there should be execute() fn at the last to execute the sql query

craft()->db->createCommand()
->insert('mytablename', array(
    'field1'    => 'foo',
    'field2'    => 'bar'
))
->execute();

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.