CakePHP数据不保存/添加到数据库

时间:2013-03-04 12:09:27

标签: php sql cakephp

提交数据只会重新加载页面,CakePHP不会给出任何错误或消息。 代码遵循与博客教程相同/相似的结构。

观看代码

        <?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');
        ?>

控制器代码

    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.');
        }
    }
}

型号代码

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

导出的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 ;

3 个答案:

答案 0 :(得分:4)

您指定了错误的请求'方法';

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

应该是:

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

我怀疑你对CakePHP上的例子感到困惑,它们使用'post' Model 。但是,这一行是检查用于访问页面的请求类型,例如postgetput

通过检查正确的请求方法,CakePHP将仅在表单发送/提交时插入/更新数据,否则表单只是显示而不更新数据库

答案 1 :(得分:0)

您忘记在模型中定义name属性。

var $name = 'Sm';

答案 2 :(得分:0)

就在几分钟前,我遇到了同样的问题。我的问题更奇怪了。在我的控制器中,我使用了这样的东西:

if( $this->MyModel->save( $this->request->data ) ) {
    //positive. proceed.....
}
else {
    //negative. show error
    pr( $this->MyModel->validationErrors );
}

正如你所看到我处理了否定的情况,但我仍然看不到任何东西。即使在我的模型中,我使用beforeSave和afterSave来检查。在我的beforeSave模型中,我可以看到一个完全格式化的数组已准备好保存,但是我的afterSave没有触发,这意味着数据没有被保存。因此,我应该看到我的控制器出错。仍然没有解决方案。

现在这就是我弄清楚问题的方法。我检查了表格,数据将被保存到。该表有许多具有NOT NULL属性的列。我保存的数据有一些NULL值的字段。所以从理论上讲,我应该在控制器中看到validationErrors作为一个原因,但不幸的是它没有显示出来。将这些字段设置为可空可以解决我的问题。所以我的建议是检查哪些字段可能有NULL值并设置为可空,并确保NOT NULL字段有一些值。

希望这会有所帮助。干杯!!!