0

I have a basic query as follows

$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";

I have to modify this query to create a query where we have multiple subject codes fetched from an array.

$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);

Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....

Now I want to the original query to be modified something as follows

$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";

Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.

How can i accomplish this?

Bibhudatta Sahoo
  • 4,808
  • 2
  • 27
  • 51

7 Answers7

1

You can use Mysql In operator Like this

SELECT * FROM files WHERE subject_code in ('SC1','SC2')";

You can achieve ('SC1','SC2') by using implode php function,
like this:

$subCodes = implode("','", $subject_array ); 
SELECT * FROM files WHERE subject_code in ('".$subCodes ."')"
Bibhudatta Sahoo
  • 4,808
  • 2
  • 27
  • 51
1
$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
$codes=(array)$result; //this will convert it in normal array. old school typecasting ;)
$codes=array_values($codes);
$query = "SELECT * FROM files WHERE subject_code in (".implode(",",$codes).")";
//considering result is an object of subject codes.

CODE UPDATED ABOVE as it is an object.

You don't need to append to the first query. Just build a new query using MySQL in operator and php implode function.

Ninad Ramade
  • 256
  • 2
  • 9
1

You can use implode to convert array to string comma delimited

like below:

$branch_array = array('subject1', 'subject2', 'subject3');
$branch = implode("','", $subject_array ); 

$query1="SELECT subject_code FROM subject WHERE sbranch  in ('".$branch."')";

result:

 'subject1', 'subject2', 'subject3' 

Hope that resolve your issue

Fernan Vecina
  • 144
  • 1
  • 8
1

You can use a subquery like this:

$query = 'SELECT * FROM files 
WHERE subject_code IN (
    SELECT subject_code FROM subject WHERE sbranch = "' . $branch . '"
)';
codeit
  • 111
  • 8
0
SELECT * FROM files WHERE subject_code in ('SC1','SC2')
Ravi Kumar
  • 313
  • 2
  • 13
0

You can amend your php array to comma delimited string of SubjectCodes.

then:

$query1="SELECT * FROM files WHERE subject_code in (".$NewString.") ";

$NewString will look something like this:

"'SC1', 'SC2', 'SC3'"
zartab
  • 1
  • 2
0
 $result = array(0=>'SC1',1=>'SC2');  //this is your array
 $branch = implode("','", $result );
 $query .= "
   SELECT * FROM files WHERE subject_code in ('".$branch."') "; //this is query
Dharmendra Singh
  • 1,186
  • 12
  • 22