【问题标题】:inserting into a database only the filled inputs in a html table仅将 html 表中的填充输入插入数据库
【发布时间】:2015-08-21 20:58:41
【问题描述】:

我正在构建一个使用 jQuery DataTables 插件的 Laravel 5 应用程序。在数据表中,我每行有 3 个输入字段。我想要做的是插入所有已填充的行输入。在每一行中,您必须填写所有 3 个输入,以便将数据发布到数据库中。 (数据库是 sql server。)我尝试了一些东西,但它不起作用。这是我在控制器存储方法中尝试过的:

$dates = $request->get('month');
    $values = $request->get('value');
    $comments = $request->get('comment');
    $reports = []; // this will keep what we input in our DB
    /*if(!empty($row['month']) && !empty($row['value']) && !empty($row['comment'])){
        foreach($row as $rows){
            $index = +1;
        }
    }*/
    if(!empty($dates) && !empty($values)){
    for($i = 0; $i < count($dates); $i++)
    {
        //here i am dividing month and year
        $date = explode('-', $dates[$i]);
        $year = $date[0];
        $month = $date[1]; // <-- line 75

            $reports[] = Reports::create([
                'month' => $month,
                'year' => $year,
                'value' => $values[$i],
                'comment' => $comments[$i]
            ]);

        }
    }
    return $reports;

这会引发一个错误:

ErrorException in ReportController.php line 75:
Undefined offset: 1

我已经搜索过它,它说我正在传递一个数组而不是一个字符串。

这里是堆栈跟踪(它的一部分):

at HandleExceptions->handleError('8', 'Undefined offset: 1', 'E:\socgen\soc-gen\app\Http\Controllers\ReportController.php', '75', array('request' => object(Request), 'dates' => array('2015-06', '2015-02', ''), 'values' => array('369', '22223', ''), 'comments' => array('878', '5466', ''), 'reports' => array(object(Reports)), 'i' => '1', 'date' => array(''), 'year' => '', 'month' => '06')) in ReportController.php line 75

感谢任何帮助或提示

【问题讨论】:

  • 第 75 行的代码是什么
  • $row 是什么?它来自哪里?
  • @itachi 抱歉,这是我之前做过的测试。它应该在这里被评论
  • 为什么您要经历所有这些麻烦,只是为了将日期、月份、年份存储在不同的列中? yyy-mm-dd 日期格式没问题。
  • 我只需要月份和年份,最后我需要执行查询范围以仅过滤一年中的数据。

标签: php jquery laravel laravel-5


【解决方案1】:

php.net 上的官方文档中关于爆炸函数的内容如下。

返回一个字符串数组,每个字符串都是 string 的子字符串,通过在 string 分隔符形成的边界上拆分它而形成。

得出的结论是,php 的explode 函数仅将字符串作为参数,在您的情况下,您正在传递一个数组。我建议您首先将数组中的数据放入字符串中,然后将其传递给爆炸。例如

for($i = 0; $i < count($dates); $i++)
{
    //remove empty indexes from your array 
    array_diff( $dates[$i], array( '' ) );

    //create a new string and put your date into it.
    $dateString = $dates[$i];

    $date = explode('-', $dateString);
    $year = $date[0];
    $month = $date[1]; // <-- line 75

    //rest of your code goes here 
    }
}

【讨论】:

  • 那行不通。问题是当值被发布时,它们以数组的形式出现。我只想获取非空白的值。如果我离开最后一行没有值,我得到的只是 $dates('2015-06','2015-07','')。
  • 使用 isset 检查数组的当前索引是否为空。此外,您还可以使用 array_diff();从数组中过滤出空白索引
  • 好的,这行得通。它删除了空数组。但是当我在桌子上留下一个空行时,我仍然会遇到同样的错误
  • 将您的列更改为可为空
猜你喜欢
  • 1970-01-01
  • 2021-08-03
  • 2018-04-24
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 2021-04-20
  • 1970-01-01
相关资源
最近更新 更多