【问题标题】:SQL Error : Sending empty strings through a formSQL 错误:通过表单发送空字符串
【发布时间】:2016-12-14 21:05:59
【问题描述】:

我正在使用 Bootforms 来编辑博客上的帖子

<?php $formOptions = [
        'url' => 'user',
        'sm' => [2, 5],
        'lg' => [2, 5],
        'method'=> 'put'
    ]; ?>

    {!! BootForm::openHorizontal($formOptions)->action(route('news.update', $post)) !!}
    <input type="hidden" name="_method" value="PUT">
    {!! BootForm::text('Titre', $post->title) !!}
    {!! BootForm::text('Slug', $post->slug) !!}
    {!! BootForm::textarea('Contenu', $post->content) !!}
    {!! BootForm::submit('Editer') !!}
    {!! BootForm::close() !!}

这是我更新帖子后的 PostController 函数:

 public function update($id, Request $request)
{
    $post = Post::findorFail($id);

    $title = $request->input('title');

    $post->title = $title;
    $post->content = $request->input('Contenu');

    $request->has('save');

    $post->save();
    return redirect(route('news.index'));
}

但是一旦我编辑了我的帖子,我就会遇到这个错误,就像我发送空字符串一样:SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: update posts set title = , content = , updated_at = 2016-12-14 20:48:25 其中id = 3)

如果您发现问题出在哪里,我可以寻求帮助...

【问题讨论】:

  • 错误再清楚不过了,它告诉您您正在尝试在数据库中插入一个空的(NULL)“标题”字段,并且该字段被定义为非空。
  • 我知道,我说我知道它正在发送空字符串。问题是我不知道如何解决它。但是感谢您的帮助..
  • 哎呀,没意识到,抱歉讽刺了。

标签: php sql database laravel


【解决方案1】:

您似乎在表单中使用了无效参数。如果你想使用默认值,你应该像 github 中的例子一样:

https://github.com/adamwathan/bootforms

BootForm::text('Titre', 'title')->defaultValue($post->title);

现在你使用 $post->title 作为字段名,所以 $_POST['title'] 只是空的。

【讨论】:

  • 哦,是的!那很愚蠢,但我无法弄清楚。谢谢,知道了就可以了
【解决方案2】:

可能有两件事可以做。

1) 您应该允许title 列允许空值。 ALTER TABLE tableName MODIFY table VARCHAR(200);

2) 您可以先检查是否设置了标题,如果没有设置,则显示相应的错误消息。

public function update($id, Request $request)
{
    $post = Post::findorFail($id);

    $title = $request->input('title');
    /*
     First check if tile is not empty
    */
     if (empty($title)){
        //show error message // echo 'Please fill in title or whatever';
     }else{

       $post->title = $title;
       $post->content = $request->input('Contenu');

       $request->has('save');

       $post->save();
       return redirect(route('news.index'));
     }
}

标题不应该为空似乎很直观,所以在我的建议中你应该先尝试第二种方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多