php数组到sqlite3 DB

时间:2013-06-01 10:50:29

标签: php sqlite php-5.4

*我正在尝试将本地数组值$ productname放入sqlite3表中,该数组如下所示:

[0] usb 16gb
[1] monitor 16"
[2] dual batteries
[3] multi blender pro

依此类推*

// Prepare INSERT statement into sqlite3
  $insert = "INSERT INTO products (name) 
            VALUES (:name)";

  $stmt = $db->prepare($insert);

  // Bind parameters to statement variables
  $stmt->bindParam(':name', $title);

  // Loop all product title and execute
   foreach ($productname as $i)
  {
        // Set values to bound variables
        $title = $i['name'];
        // Execute statement
         $stmt->execute();
  }

  $result= $db->query('SELECT * FROM products');
    foreach($result as $row) 
     {
        echo "Id: " . $row['id'] . "\n";
        echo "Title: " . $row['name'] . "\n";
     }

虽然这确实有效,但会打印出

Id: 1
Title: U
Id: 2 
Title: M
Id:3 
Title: D
Id:4 
Title: M 

我哪里错了?它不会打印出整个字符串(产品名称)......? 它也会自己迭代80次,而实际上只有4个左右的标题。基本上我想将一个php数组放入一个sqlite3表列(productTitle)

1 个答案:

答案 0 :(得分:0)

简而言之,title变量在声明之前使用。它应该在循环内部使用,如下所示:$stmt->bindParam(':name', $i['name']);