I'm trying to save data to more tables using CakePHP (2.4.6).
I have Posts/add.tcp file:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body', array('rows' => '3'));
echo $this->Form->end('Save Post');
?>
And method add in PostsController file:
public function add() {
if ($this->request->is('post')) {
$this->request->data['Post']['user_id'] = $this->Auth->user('id');
$titulek = $this->request->data['Post']['title'];
$uid=$this->request->data['Post']['user_id'];
$body=$this->request->data['Post']['body'];
$sqla = "INSERT INTO posts (title,created,user_id) VALUES ('$titulek', NOW(),'$uid')";
$sqlb = "INSERT INTO forums (user_id,post_id,text,created) VALUES ('$uid',NULL,'$body', NOW())";
if ($this->Post->query($sqla)) {
if ($this->Post->query($sqlb)) {
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
}
}
}
But it doesn't work as intended. Only $sqla
query is actually saved to the database. $sqlb
query isn't executed at all and at the end I'm not redirected to another page. It's interesting that if I reverse the order of queries (e.g. current $sqlb
query becomes $sqla
query and $sqlb
query becomes $sqla
query the INSERT INTO forums
query executes correctly but INSERT INTO posts
isn't, so it seems that both queries are written correctly and for some reason only first of them executes). What am I doing wrong? I just want to insert custom query into more tables in one action. Thanks in advance for any help.