2014-02-23 102 views
0

嗨,我想插入2個陣列在數據庫表中,並得到以下:不能插入數組表MySQL的PHP​​

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."'"); 
    } 

回答

0

我構建查詢而獲取的結果,那麼concatinate件,以形成最終的INSERT查詢:

$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)); 
+0

警告:非法字符串偏移'customer – user3343374

+0

對不起,我錯誤地寫了$ query- >行而不是$ query-> rows,我現在編輯它。 –

+0

非常感謝! – user3343374

0

你不能用數組串聯字符串。 $ids$sums必須是一個字符串。

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."')"); 
} 

請注意,您引號括起來的表名,但實際上你不應該,如果你願意,你可以使用反引號( `)

+0

它可以做的更好 - 一個SQL查詢。 – Artur

+0

我還會使用準備好的語句進行重複性語句(https://php.net/manual/de/mysqli.quickstart.prepared-statements.php) – Sebus

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."'");