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 ?

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.

Try this

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