Passing CONCATENATED sql using foreach loop of php

Viewed 32

I am a learner and student i am making a q/a forum for that i have to pass a concatenated sql, so i am trying to create string that i have to pass my sql statement using foreach loop in php, but i am not getting result as desired,

This is my array here (generated using database given is var_dump result):

array(3) { [0]=> string(0) "" [1]=> string(10) "mrun@g.com" [2]=> string(12) "shorya@g.com" };

 <?php
        foreach ($_array_following as $__name){
            $__feed_flist = "";
            if($__name){
                $__feed_flist .= "'";
                $__feed_flist .= $__name;
                $__feed_flist .= "', ";
            }
            }
            $_selected_names = substr($__feed_flist, 0, -1);
            echo var_dump($_selected_names);
          ?>   

What is want is this:

'mrun@g.com', 'shorya@g.com'

so that i can pass it to my sql:

$sql = "SELECT * FROM `user` WHERE `user_email` IN ( $_selected_names);";

but what i am getting is just the last element in the array:

'shorya@g.com'

Please tell me what to do.

1 Answers

Instead of doing your code you can use below code.

$arrayEmailList =   array('','mrun@g.com','shorya@g.com');
$EmailList      =   "'".implode("','",array_filter($arrayEmailList))."'";
$Query          =   "SELECT * FROM `user` WHERE `user_email` IN ( $EmailList);" ;

echo $Query;

//Output is

SELECT * FROM `user` WHERE `user_email` IN ( 'mrun@g.com','shorya@g.com');
Related