0

i have an array

variable $smt_database = 257, 259, 261

Array ( [0] => 257, 259, 261 ) 

how can i insert this variable $smt_database in database like this :

$sql = "SELECT first_name FROM '.TABLE_PREFIX.'members 'WHERE member_id IN ($smt_database)";

when i echo the sql it show array like below :

SELECT first_name FROM '.TABLE_PREFIX.'members 'WHERE member_id IN (Array)

how can i change so it can like sql below :

SELECT first_name FROM '.TABLE_PREFIX.'members 'WHERE member_id IN (257, 259, 261)

i know we must use implode and explode but i do not know how to implement them.

7
  • Where does the $smt_database variable come from? Is it user supplied data? Commented Aug 11, 2014 at 5:41
  • it from database.. but i have the answer already thanks. Commented Aug 11, 2014 at 5:43
  • 1
    You store comma separated data in your columns? That's a SQL anti-pattern ... besides that, you can just use ${stm_database[0]}. Commented Aug 11, 2014 at 5:44
  • yes.. hehe.. i dunno anti pattern.. i saw one of the answer below.. nice approach.. i never though of that Commented Aug 11, 2014 at 5:46
  • See also this answer for more information on "Jaywalking" anti-pattern. Commented Aug 11, 2014 at 5:47

3 Answers 3

2

simple use implode

$in_text = implode(",", $smt_database);

// now use this variable in sql like

$sql = "SELECT first_name FROM '.TABLE_PREFIX.'members 'WHERE member_id IN ($in_text)";

above will work if the values in array are numeric

So if value in array are not numeric you need to single quotes on your value try

update 2 :

$new_array = array();
foreach($your_array as $val)
{
    $new_array[] = "'".$val."'";
}

// now use implode

 $in_text = implode(",", $new_array);

  // now use this variable in sql 
Sign up to request clarification or add additional context in comments.

2 Comments

implode is useless for Array ( [0] => 257, 259, 261 ) its useful for Array ( [0] => 257,[1]=> 259,[2]=> 261 )
thanks .. i just missing the implode .. $mid1 = implode(',', preg_replace('/\s+/', '', $smt_database));
1

Use with impload and FIND_IN_SET because IN operator do not work on String value.

$your_text = implode(",",$smt_database);

$sql = "SELECT first_name FROM '.TABLE_PREFIX.'members 'WHERE FIND_IN_SET(member_id,$your_text)";

1 Comment

bro , is missing in implode
1

Use this:

$sql = "SELECT first_name FROM '.TABLE_PREFIX.'members 'WHERE member_id IN (".$smt_database[0].")";

assuming you have array $smt_database = Array ( [0] => 257, 259, 261 )

1 Comment

hi nice way to solve my problems.. thanks for the knowledge sharing.. never thought the way of solving this kind of problems like this..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.