-4

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 ?

4
  • 3
    Have you tried something? Show us your code... Commented May 9, 2015 at 12:42
  • 1
    As mentioned above, you should show your code so that the community can point you back in the right direction; if you have not yet attempted any code, the following section of CodeIgniter's documentation may be of some use: ellislab.com/codeigniter/user-guide/database/… Commented May 9, 2015 at 12:45
  • im using implode funciton it is show message 'SELECT * FROM add_to_cart WHERE 8,35,1 ' but i need associate array Commented May 9, 2015 at 12:46
  • @Ben Broadley i know that codeigniter active record but i need all function like codeigniter to php, any way there ? Commented May 9, 2015 at 12:48

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.