Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to get elements of an array, and put it to MySQL query using PHP like this:

$ArrayOne = {3, 5, 8, 2};
$sql = SELECT * from myTable WHERE id1='3' and id2='5' and id3='8' and id4='2';

I do it like this, but it's failed:

for ($i=0; $i<count($ArrayOne); $i++) {
  $element.$i = $ArrayOne[$i];
}
  $sql = ("SELECT * from myTable WHERE id1=". $element.$i ." and id2=". $element.$i ." and id3=". $element.$i ." and id4=". $element.$i .");

I think the $element.$i has the same value, but I don't know how to get the different value of Array element. And if I do like this, it's also wrong.

for ($i=0; $i<count($ArrayOne); $i++) {
  $element.$i = $ArrayOne[$i];    
  $sql = ("SELECT * from myTable WHERE id1=". $element.$i ." and id2=". $element.$i ." and id3=". $element.$i ." and id4=". $element.$i .");
}

Can any body give the solution?

share|improve this question
 
May I encourage you to instead visit php.net and read up on the PDO library. If you are going to start learning how to make php db queries it would be better to learn how to do it securely and efficiently as we'll. –  KenK Sep 9 at 1:16

2 Answers

up vote 1 down vote accepted

You have several mistake in your code

The first is:

$ArrayOne = {3, 5, 8, 2};

Should be:

$ArrayOne = array(3, 5, 8, 2);

2nd mistake, your $sql variable doesnt has enclosed between quotes should be $sql="your query";

if your array has a fix length you dont have need to use a loop:

$ArrayOne = array(3, 5, 8, 2);

 $sql =  "SELECT     * 
     from       myTable 
     WHERE      id1='$ArrayOne[0]'
     and        id2='$ArrayOne[1]'
     and        id3='$ArrayOne[2]'
     and        id4='$ArrayOne[3]'";

For an array of variable length you can use the @Nightmare's answer

As side note:

Read about SQL Injection

You should learn PDO, if you are starting to learn php, do it the right way

Manual

share|improve this answer
 
Peter O, KenK : thank you for your information. –  user2758001 Sep 9 at 1:59

Try this:

$count = count($ArrayOne);
for($i=0; $i<$count; $i++){
    $where_arr[$i] = 'id'.$i.'='.$ArrayOne[$i];
}

$sql = "select * from myTable where ".implode(" and ",$where_arr);
share|improve this answer
 
Thank you very much Nightmare. Yes, i think this can be the solution. –  user2758001 Sep 9 at 1:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.