尝试使用array
在数据库中插入codeigniter
。但我得到了像
错误号码:1064
您的SQL语法有错误;查看与MySQL服务器版本对应的手册,以便在第1行“0,1,2,3”VALUES('5','6','11','13')附近使用正确的语法
INSERT INTO
customer_orders
(0,1,2,3)VALUES('5','6','11','13')文件名:C:/xampp/htdocs/hari/billing-system/system/database/DB_driver.php
行号:691
控制器:
class Customer_order extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->model('orders');
}
function addnewcustomerorder()
{
$product_id = $this->input->post('product_id');
$data = array(
'product_id' => $product_id
);
//print_r($data);
$res = $this->orders->addnewcustomerorder($data);
}
型号:
function addnewcustomerorder($data)
{
if($data['product_id']!="")
{
foreach($data as $a)
{
$res=$this->db->insert('customer_orders',$a);
return $this->db->insert_id();
}
}
else
{
return false;
}
}
注意:忽略
customer_id
我如何insert
数据库中的值
答案 0 :(得分:0)
将变量命名为它们会有所帮助,因为$ data [' product_id']是一个id数组,应该是复数形式($ data [' product_ids']),这将有助于调试代码
//since product_id is an array of product ids (should change it to $data['product_ids'])
/*$data = [
'product_id' => [2,3,4,6,7]
];
*/
//var_dump($data); showing values like array(1) { ["product_id"]=> array(4) { [0]=> string(1) "5" [1]=> string(1) "6" [2]=> string(2) "11" [3]=> string(2) "13" } } i pass only product_id
function addnewcustomerorder($data)
{
$orders = [];
foreach($data['product_id'] as $product_id){
if($product_id AND $product_id != "")
{
$this->db->insert('customer_orders',['product_id'=>$product_id]);
$orders[] = $this->db->insert_id();
}
}
return $orders;
}
答案 1 :(得分:0)
首先在数据库查询中使用forech不是建议。 Codeigniter具有insert_batch功能,可以向数据库添加多行。你应该使用它。
现在出现问题,如果这是您要插入的数组,请参考您的评论:
0
Process finished with exit code 0
然后这是可以帮助你的代码。
你的控制器:
Array
(
[product_id] => Array
(
[0] => 1
[1] => 3
[2] => 4
[3] => 5
)
)
你的模特:
function addnewcustomerorder()
{
$product_id = $this->input->post('product_id');
$res = $this->orders->addnewcustomerorder($product_id);
}
有关信息:以下是function addnewcustomerorder($product_id)
{
if($data['product_id']!="")
{
$your_product_array = '';
foreach($product_id as $pro_id)
{
$your_product_array[] = array('product_id'=>$pro_id);
}
$this->db->insert_batch('customer_orders',$your_product_array);
// This above code inser all the row at once.
// I am suggesting to use database transaction.
return true;
}
else
{
return false;
}
}
:
your_product_array
希望它对你有所帮助。
答案 2 :(得分:-1)
将您的模型更改为此
假设您的order_id
是自动递增而customer_id
将为空或为空(因为您不发送该值)
function addnewcustomerorder($data){
if($data['product_id']!="") {
foreach($data as $a){
$res=$this->db->insert('customer_orders', array('product_id' => $a));
return $this->db->insert_id();
}
}
else{
return false;
}
}