[英]codeigniter: how to put the value of the array into a specific table column?
我有这样的数组
array(12) {
[0]=> string(1) "3"
[1]=> string(1) "3"
[2]=> string(1) "5"
[3]=> string(1) "3"
[4]=> string(1) "4"
[5]=> string(1) "3"
[6]=> string(1) "3"
[7]=> string(1) "3"
[8]=> string(1) "2"
[9]=> string(1) "3"
[10]=> string(1) "2"
[11]=> string(1) "3"
}
数组是动态的,因此可以随时更改数组值
我也有一个具有这样结构的mysql表
|id|bobot_c1|bobot_c2|bobot_c3|bobot_c4|bobot_c5|bobot_c6|bobot_c7|bobot_c8|bobot_c9|bobot_c10|bobot_c11|bobot_c12|
-------------------------------------------------------------------------------------------------------------------
| | | | | | | | | | | | | |
-------------------------------------------------------------------------------------------------------------------
id是auto_increment
如何在数据库表中输入键数组: "3", "3", "5", "3"
和其他?
因此对于值索引[0] ,我进入bobot_c1列, 索引[1]进入bobot_c2列,等等。
谢谢!
我假设您已经了解如何将数据从控制器传递到模型的codeigniter的基础知识
这是CodeIgniter的用户指南
// construct an array with indexes like this
// the indexes pertains to the table columns
// and the value will be the indexes value
$data = array(
"bobot_c1" => "3",
"bobot_c2" => "3",
"bobot_c3" => "5",
"bobot_c4" => "3",
"bobot_c5" => "4",
"bobot_c6" => "3",
"bobot_c7" => "3",
"bobot_c8" => "3",
"bobot_c9" => "2",
"bobot_c10" => "3",
"bobot_c11" => "2",
"bobot_c12" => "3"
);
// table name you want to insert data
$table = "table_name"
// use codeigniter active record to
// insert data
$this->db->insert($table, $data);
像这样构造sql:
$sql = "INSERT INTO table (columns here) " .
"VALUES (".implode($array,",").")";
$this->db->query($sql);// no need to add id column in sql since it is auto increatented value
创建另一个这样的数组:
$dataArray = (
'bobot_c1' => $array[0],
'bobot_c2' => $array[1],
'bobot_c3' => $array[2],
'bobot_c4' => $array[3],
.
.
.
);
类似地,添加更多列并将$ dataArray插入数据库。
第一
第二
这就是查询
INSERT INTO table_name (id, bobot_c1, bobot_c2, bobot_c3, bobot_c4, bobot_c5, bobot_c6, bobot_c7, bobot_c8, bobot_c9, bobot_c10, bobot_c11, bobot_c12)
VALUES (NULL, CONVERT(INT, $index[0]), CONVERT(INT, $index[1]), CONVERT(INT, $index[2]), CONVERT(INT, $index[3]), CONVERT(INT, $index[4]), CONVERT(INT, $index[5]), CONVERT(INT, $index[6]), CONVERT(INT, $index[7]), CONVERT(INT, $index[8]), CONVERT(INT, $index[9]), CONVERT(INT, $index[10]), CONVERT(INT, $index[11]));
这是将查询转换为CodeIgniter的教程
/*
class Myclass {
var $title = 'My Title';
var $content = 'My Content';
var $date = 'My Date';
}
*/
$object = new Myclass;
$this->db->insert('mytable', $object);
// Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')
尝试这个:
$cols = 11;
$sql = "INSERT INTO table_name ( ";
for($i=0; $i<$cols; $i++){
if($i!=0)
$sql .=", bobot_c" . ($i+1);
else
$sql .="bobot_c" . ($i+1);
}
$sql .=" ) VALUES( ";
for($i=0; $i<$cols; $i++){
if($i!=0)
$sql .=", '" .$array[$i] . "'";
else
$sql .="'" .$array[$i] . "'";
}
$sql .=" )";
$query = $this->db->query($sql);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.