PHP / MYSQL将数组转换为WHERE子句

时间:2015-05-09 12:41:49

标签: php mysql

转换此数组

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

查询

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

还有如何使用codeigniter主动记录功能以任何方式或库提供php?

2 个答案:

答案 0 :(得分:1)

使用implodearray_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)));

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 );

创建查询

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

$query输出:

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

<强>笨

在您的控制器中,获取数据

$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);

现在,您可以在视图中使用$products变量,它已找到所有产品。

答案 1 :(得分:0)

试试这个

$array  = array("user_id"=>"8","product_id"=>"35","quantity"=>"1");
$clauses = array();
foreach ($array as $field => $value) {
  $clauses[] = "$field='$value'";
}
$where_clause = join(" and ",$clauses);
echo "select * from tbl_name where " . $where_clause;