无法将数组插入表mysql php

时间:2014-02-23 14:56:06

标签: php opencart

您好我正在尝试在数据库表中插入2个数组并获得以下内容:

Warning: Invalid argument supplied for foreach() in 
C:\xampp\htdocs\sport\admin\model\competition\newsletter.php on line 9

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\sport\admin\model\competition\newsletter.php on line 12

Notice: Array to string conversion in C:\xampp\htdocs\sport\admin\model\competition\newsletter.php on line 18

Notice: Array to string conversion in C:\xampp\htdocs\sport\admin\model\competition\newsletter.php on line 18Notice: Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''customer_transaction'(customer_id,amount) VALUES'Array,Array'' at line 1

Error No: 1064
INSERT INTO 'customer_transaction'(customer_id,amount) VALUES'Array,Array' in C:\xampp\htdocs\sport\system\database\mysql.php on line 49

我如何解决所有这些问题。这是代码: 这是opencart模块文件

$sql = "SELECT DISTINCT competition_rate, customer_id FROM " . DB_PREFIX . "customer  WHERE competition_rate NOT LIKE 0";
    $query = $this->db->query($sql);
$rates = array();
$customer_ids = array();
foreach($query->row['competition_rate'] as $result){
    $rates[] = $result * $data['name'];
}
foreach($query->row['customer_id'] as $result2){
    $customer_ids[] = $result2;
}

$sums = $rates;
$ids = $customer_ids;
$this->db->query("INSERT INTO 'customer_transaction'(customer_id,amount) VALUES'".$ids.",".$sums."'");
    }

4 个答案:

答案 0 :(得分:1)

我宁愿在$row中循环,然后在任何迭代中进行一次INSERT查询

$query = $this->db->query($sql);

foreach($query->row as $result){
   $rates = $result['competition_rate'] * $data['name'];
   $ids = $result['customer_id'];

   $this->db->query("INSERT INTO customer_transaction (customer_id,amount) VALUES ('".$ids.",".$rates."')");
}

请注意,您使用引号包围了表名,但实际上您不应该使用反引号(`)

答案 1 :(得分:0)

您不能将字符串与数组连接。 $ids$sums必须是字符串。

答案 2 :(得分:0)

试试这个,您的表名不需要包含在'values() ()括号内。

 $this->db->query("INSERT INTO `customer_transaction` (customer_id,amount)                               
   VALUES ('$ids','$sums') ");
        ..^                    ^...

而不是

 $this->db->query("INSERT INTO 'customer_transaction'(customer_id,amount) VALUES'".$ids.",".$sums."'");

答案 3 :(得分:0)

我在获取结果时构建查询,然后连接各个部分以形成最终的插入查询:

$arr = array();
foreach($query->rows as $result){
   $arr []= '('. implode(', ', array($result['customer_id'], $result['competition_rate'] * $data['name'])) . ')';
}
$this->db->query("INSERT INTO 'customer_transaction'(customer_id,amount) VALUES " . implode(', ', $arr));