Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP data not saving/adding to database

Tags:

sql

php

cakephp

Submitting the data only reloads the page, no errors or messages is given by CakePHP. The code follows the same/similar structure as the blog tutorial.

The view code

        <?php
        echo $this->Form->create('Sm');
        echo $this->Form->input('recievers', array('rows' => '1'));
        echo $this->Form->input('subject');
        echo $this->Form->input('message');
        echo $this->Form->end('SEND');
        ?>

Controller code

    public function send() {
    if ($this->request->is('sm')) {
        $this->Sm->create();
        if ($this->Sm->save($this->request->data)) {
            $this->Session->setFlash('Sms has been added to the database');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to send sms.');
        }
    }
}

Model code

class Sm extends AppModel {
public $validate = array(
    'subject' => array(
        'rule' => 'notEmpty'
    ),
    'message' => array(
        'rule' => 'notEmpty'
    ),
    'recievers' => array(
        'rule' => 'notEmpty'
    )
); }

Exported SQL

    CREATE TABLE IF NOT EXISTS `sms` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `subject` varchar(150) DEFAULT NULL,
  `message` text,
  `sender` varchar(50) DEFAULT NULL,
  `recievers` text,
  `sent` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

1 Answers

You've specified an incorrect request 'method';

if ($this->request->is('sm')) {

Should be:

if ($this->request->is('post')) {

I suspect you got confused by the examples on CakePHP, which use a 'post' Model. However this line is to check the type of request used to access the page, e.g. post, get, put.

By checking for the right request method, CakePHP will only insert/update the data is the form is sent/submitted, otherwise the form is just shown without updating the database

like image 111
thaJeztah Avatar answered Jan 01 '26 07:01

thaJeztah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!