在我的选择选项中,我有两个数字的值示例 value =" 163,162"
我有一个模型函数,可以插入第一个值为类别ID 163
Var Dump
array(2) { [0]=> string(3) "163" [1]=> string(4) " 162" }
问题:我需要添加parent_id = " . $this->db->escape($category['parent_id']) . "
但不确定如何获取第二个值并将其设置为parent_id = " . $this->db->escape($category['parent_id']) . "
父ID将为示例162
模型功能
public function page_update($page_id, $data) {
$this->db->query("DELETE FROM " . $this->db->dbprefix . "page_to_category WHERE page_id = '" . (int)$page_id . "'");
if (isset($data['categories'])) {
foreach ($data['categories'] as $category) {
//$data_sample = explode(',', $category['category_id']);
//var_dump($data_sample);
//exit;
$this->db->query("INSERT INTO " . $this->db->dbprefix . "page_to_category SET
page_id = '" . (int)$page_id . "',
category_id = " . $this->db->escape($category['category_id']) . "
");
}
}
}
查看
<div class="form-group">
<label class="col-sm-2">Category</label>
<div class="col-sm-10">
<select class="form-control" name="categories[1][category_id]">
<option value="0">-- No Category Required --</option>
<?php foreach ($categories as $category) {?>
<?php if ($category['category_id'] == $category_id) {?>
<option value="<?php echo $category['category_id'];?>, <?php echo $category['parent_id'];?>" selected="selected">
<?php echo $category['name'];?></option>
<?php } else { ?>
<option value="<?php echo $category['category_id'];?>, <?php echo $category['parent_id'];?>"><?php echo $category['name'];?></option>
<?php }?>
<?php }?>
</select>
</div>
</div>
答案 0 :(得分:2)
使用Codeigniter语法非常简单和可取,如果你想查看一下,这段代码与@Arcanix的答案相同但使用CI Active Record语法,
public function page_update($page_id, $data)
{
$this->db->delete('page_to_category', array('page_id' => (int)$page_id));
if (isset($data['categories']))
{
foreach ($data['categories'] as $category)
{
$data_sample = array_map("trim",explode(',', $category['category_id']));
$insert_data = array(
'page_id' => (int)$page_id,
'category_id' => $this->db->escape($data_sample[0])
);
$this->db->insert('page_to_category', $insert_data);
}
}
}
答案 1 :(得分:1)
答案是这样的:
public function page_update($page_id, $data) {
$this->db->query("DELETE FROM " . $this->db->dbprefix . "page_to_category WHERE page_id = '" . (int)$page_id . "'");
if (isset($data['categories'])) {
foreach ($data['categories'] as $category) {
$data_sample = array_map("trim",explode(',', $category['category_id']));
//Here $data_sample[0] will always be your category id and $data_sample[1] will be your parent id
$this->db->query("INSERT INTO " . $this->db->dbprefix . "page_to_category SET
page_id = '" . (int)$page_id . "',
category_id = " . $this->db->escape($data_sample[0]) . "
");
}
}
}
此处$ data_sample [0]将始终是您的类别ID,$ data_sample [1]将是您的父ID
答案 2 :(得分:0)
如果要进行多次插入,可以使用活动记录来执行此操作。首先创建要插入的array
数据,然后使用insert_batch
方法
$insertdata = array(
array(
'email' => 'email' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'email' => 'some data' ,
'name' => 'some data' ,
'date' => 'some data '
)
);
$this->db->insert('mytable', $insertdata);
获取更多信息