【问题标题】:SQL search and insert with an array in CodeIgniter在 CodeIgniter 中使用数组进行 SQL 搜索和插入
【发布时间】:2013-12-30 15:29:38
【问题描述】:

我正在尝试使用从下拉框中获取的数组在我的数据库中进行搜索,然后在搜索该实例后尝试将其插入到我的表中。这是我到目前为止所拥有的。

控制器:

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 循环,它循环 $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');

我希望数组中的每个值都发生这种情况,所以下次我们将通过 goodbye 进行搜索,id 为 2 并将插入到 table2

【问题讨论】:

    标签: php sql codeigniter


    【解决方案1】:

    要在 where 子句中使用数组,您可以这样做:

    $ids = join(',',$array);  
    $sql = "SELECT * FROM table WHERE id IN ($ids)";
    

    【讨论】:

    • 好的,你能告诉我为什么我需要使用连接吗? , 需要什么?
    • 你能给我看一个你的例子吗:$value?您希望一个字段可以等于多个值吗?所以你必须创建一个查询,如:WHERE Table3 IN (exp1, exp2, etc..) 也许我不明白你的问题
    • 立即查看帖子
    【解决方案2】:

    @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

    【讨论】:

    • 当我尝试这个方法时,我仍然得到同样的未知列错误,知道为什么吗?
    • 你确定你的table3中有一个名为'value'的列吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 2013-04-07
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多