SQL错误:通过表单

时间:2016-12-14 21:06:00

标签: php sql database laravel

我使用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]:完整性约束违规:1048列&#39;标题&#39;不能为空(SQL:update posts set title =,content =,updated_at = 2016-12-14 20:48:25其中id = 3)

如果您发现问题出在哪里,我可以使用一些帮助...

2 个答案:

答案 0 :(得分:1)

看起来您在表单中使用了无效参数。如果你想使用默认值,你应该在github:

中作为例子

https://github.com/adamwathan/bootforms

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

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

答案 1 :(得分:0)

可能有两件事可以做。

1)您应该允许title列允许空值。 ALTER TABLE tableName MODIFY表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'));
     }
}

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