查询只插入一行而不是多行

时间:2018-07-01 07:21:32

标签: php pdo bulkinsert

我试图从excel工作表中插入多个值,我将所有数据从excel工作表存储到数组变量中。但是当我插入它总是只插入第一行时,我有一种方法可以通过使用PDO执行插入查询,

我的数据

array (size=4)
  1 => 
    array (size=5)
      'A' => string '*' (length=1)
      'B' => string 'Title' (length=5)
      'C' => string 'Author' (length=6)
      'D' => string 'Publication ' (length=12)
      'E' => string 'Container' (length=9)
  2 => 
    array (size=5)
      'A' => float 1
      'B' => string 'Test' (length=4)
      'C' => string 'one' (length=3)
      'D' => string 'two' (length=3)
      'E' => string 'X1' (length=2)
  3 => 
    array (size=5)
      'A' => float 2
      'B' => string 'Test' (length=4)
      'C' => string 'three' (length=5)
      'D' => string 'four' (length=4)
      'E' => string 'X2' (length=2)
  4 => 
    array (size=5)
      'A' => float 3
      'B' => string 'Test' (length=4)
      'C' => string 'five' (length=4)
      'D' => string 'six' (length=3)
      'E' => string 'X3' (length=2)

这是我的方法

public function importBooks($data, $nr)
{
    // Init query
    $this->db->query('INSERT INTO books_pre (title, author, publication, container, created_by, created_at) VALUES (:title, :author, :publication, :container, :created_by, now())');

    for ($i=2; $i<$nr; $i++) {
        // Bind values
        $this->db->bind(':title', $data[$i]['B']);
        $this->db->bind(':author', $data[$i]['C']);
        $this->db->bind(':publication', $data[$i]['D']);
        $this->db->bind(':container', $data[$i]['E']);
        $this->db->bind(':created_by', $_SESSION['user_id']);

        // Execute query
        if ($this->db->execute()) {
            return true;
        } else {
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

this answer将结束方法的执行-并退出循环。引用手册:

  

如果从函数中调用,则return语句立即   结束当前函数的执行,并返回其参数为   函数调用的值。

要使此工作轻松进行,我只会在return false失败时$this->db->execute(),而在方法结束时return true才这样做,就像这样:

public function importBooks($data, $nr)
{
    // Init query
    $this->db->query('INSERT INTO books_pre (title, author, publication, container, created_by, created_at) VALUES (:title, :author, :publication, :container, :created_by, now())');

    for ($i=2; $i<$nr; $i++) {
        // Bind values
        $this->db->bind(':title', $data[$i]['B']);
        $this->db->bind(':author', $data[$i]['C']);
        $this->db->bind(':publication', $data[$i]['D']);
        $this->db->bind(':container', $data[$i]['E']);
        $this->db->bind(':created_by', $_SESSION['user_id']);

        // Execute query
        if (!$this->db->execute()) {
            return false;
        }
    }

    return true;
}

但是,如果我不得不重写这段代码,我个人可能会破坏数据数组并将其全部插入一个查询中。