我正在尝试使用从下拉框中获取的数组在我的数据库中搜索,然后在搜索该实例后,我尝试将其插入到我的表中。这是我到目前为止所拥有的。
控制器:
public function insertTable() {
$text = $this->input->post('text');
$value['value'] = $this->input->post('value');
print_r($value);
$data = $this->myModel->insertTo($value,$text);
}
模型:(注意table1具有自动递增的id值,这是table2中的外键)
public function insertTo($value,$text){
$this->db->insert('table1', array('text' => $text);
$id = $this->db->insert_id();
foreach ($value as $v) {
$query = $this->db->get_where('Table3', array('value' => $v));
$result = $query->result();
foreach ($result as $row) {
$vID = $row->vID;
}
$this->db->insert('Table2', array('ID' => $id, 'vID' => $vID));
}
}
因为你可以看到我首先向table1插入一个值并获取其中的主键id
值,然后我有一个foreach
循环,它循环{{1}中的每个值数组。我在我的数据库中查询这个保存值并插入。这样做虽然我收到以下错误:
$value
所以我的问题是我哪里出错了?我应该如何使用值数组查询数据库,然后将其插入数据库?
实例的一个例子是:
Error Number: 1054
Unknown column 'Array' in 'where clause'
SELECT * FROM (`Table3`) WHERE `value` = Array
Filename: /Applications/MAMP/htdocs/CI/models/myModel.php
Line Number: 24
我希望这对数组中的每个值都有效,因此下次我们将按$value = 'hello','goodbye','morning';
//lets say when the array value is 0
$query = $this->db->get_where(table3, array('value' => 'hello');
//say this query returns 1
$this->db->insert('Table2', array('ID' => $id, 'vID' => '1');
进行搜索,ID为goodbye
,并且会插入2
答案 0 :(得分:0)
要在where子句中使用数组,可以这样做:
$ids = join(',',$array);
$sql = "SELECT * FROM table WHERE id IN ($ids)";
答案 1 :(得分:0)
@ Tosx的答案是正确的,但要扩展它并提供Codeigniter Active记录实现:
您可以使用ActiveRecord链来构建查询:
$valueArray = array('Frank', 'Todd', 'James');
$this->db->select('vID')->from('table3')->where_in('value', $valueArray);
$query = $this->db->get();
// Produces: SELECT * FROM table3 WHERE value IN ('Frank', 'Todd', 'James')
或者,您可以使用关联数组来搜索多个列:
$array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
$query = $this->db->get(table3);
// Produces: SELECT * FROM table3 WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
这里有关于CI ActiveRecord的精彩文档:http://ellislab.com/codeigniter/user-guide/database/active_record.html#select