dqhgjay5753 2015-05-09 12:41
浏览 85
已采纳

PHP / MYSQL将数组转换为WHERE子句[关闭]

Convert this array

array("user_id"=>"8", "product_id"=>"35", "quantity"=>"1")

to query

select * from tbl_name where user_id='8' and product_id='35' and quantity='1'

And also how to use codeigniter active record function to php any way or library available ?

  • 写回答

2条回答 默认 最新

  • doudu2591 2015-05-09 12:51
    关注

    Use implode and array_map.

    <?php
    $where_arr = array("user_id"=>"8", "product_id"=>"35", "quantity"=>"1");
    $where = implode(' AND ', array_map(function ($value, $key) { return "`". $key . "`='" . $value . "'"; }, $where_arr, array_keys($where_arr)));
    

    OR array_walk

    $where_arr = array("user_id"=>"8", "product_id"=>"35", "quantity"=>"1");
    array_walk($where_arr, function (&$value, $key) { $value = "`". $key . "`='" . $value . "'"; });
    $where = implode(' AND ', $where_arr );
    

    Create query

    $query = 'SELECT * FROM `tbl_name` WHERE '.$where;
    

    $query output:

    SELECT * FROM `tbl_name` WHERE `user_id`='8' AND `product_id`='35' AND `quantity`='1'
    

    CodeIgniter

    In your controller, get data

    $where_arr = array("user_id"=>"8", "product_id"=>"35", "quantity"=>"1");
    $results['products'] = $this->db->get_where('tbl_name', $where_arr)->result();
    
    $this->load->view('your_view_name', $results);
    

    Now you can use $products variable in your view, it has all found products.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献