[英]Active Record equivalent to this MySQL query - CodeIgniter
I just wanted some help figuring out how I would insert data that was coming out of a multiple select box, being put into a variable and then into a database. 我只是想要一些帮助,弄清楚如何将来自多选框的数据插入到变量中,然后再放入数据库中。
My database table is structured like this - Table: prd_attr
我的数据库表的结构如下:-表: prd_attr
ID | Product_ID | name | value
-------------------------------
1 | 3 | size | large
2 | 3 | size | medium
So say I have a multiple select box with the name sizes[]
, and the admin selects 2 sizes for a product to enter into the database. 假设我有一个名称为sizes[]
的多重选择框,并且管理员为产品选择2种尺寸以输入数据库。 I can get these values in the controller and put them into a variable: 我可以在控制器中获取这些值并将它们放入变量中:
$sizes = $_GET['sizes'];
and pass that variable to the model. 并将该变量传递给模型。 Once its there, I can insert the data as a MySQL query like this: 一旦到达,我就可以像这样将数据作为MySQL查询插入:
foreach ($sizes as $s)
{
$query = mysql_query("insert into prd_attr ('name', 'value') VALUES ('size','$s')");
}
But I've learned that mysql_* is deprecated, and since I'm using a framework which provides Active Records I'd like to make use of that. 但是我了解到mysql_ *已过时,并且由于我使用的是提供Active Records的框架,因此我想利用它。 I know the basics of Active Record, but since this is a foreach loop over a variable which can hold any number of values, I don't know how to include a foreach statement with Active Records. 我知道Active Record的基础知识,但是由于这是一个可以保存任意数量的值的变量的foreach循环,因此我不知道如何在Active Records中包含foreach语句。
Could someone please explain? 有人可以解释一下吗? Thank you for any help. 感谢您的任何帮助。
You can also use batch insert in codeigniter: 您还可以在codeigniter中使用批处理插入:
Try this: 尝试这个:
function insert_sizes()
{
$sizes = $this->input->get('sizes');
foreach ($sizes as $s)
{
$data[] = array(
'name' => 'size',
'value' => $s
);
}
$this->db->insert_batch('prd_attr',$data);
}
For more details: 更多细节:
http://ellislab.com/codeigniter/user-guide/database/active_record.html http://ellislab.com/codeigniter/user-guide/database/active_record.html
You can use this in Model of Codeigniter. 您可以在Codeigniter模型中使用它。 Here is a method 这是一种方法
function insert_sizes()
{
$sizes = $this->input->get('sizes');
$data['name'] = 'size';
foreach ($sizes as $s)
{
$data['value'] = $s;
$this->db->insert('prd_attr',$data);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.