Reputation: 35
I am building a query and I need to wrap my strings with a single quote
:
$sqlRome.="SELECT distinct id_jeune FROM jeunes_rome WHERE code_rome IN (";
foreach ($liste_rome as $rome):
$sqlRome.="'".$rome."'";//HERE
if ($j < count($liste_rome) - 1):
$sqlRome.=",";
$sqlRome.=") GROUP BY id_jeune HAVING COUNT(*)=" . $j;
I did it before, but I can not remember! It must be simple I guess.
Upvotes: 1
Views: 617
Reputation: 91734
You are doing that just fine, apart from any potential sql injection problems.
You do have a problem with your block-structure however, use { ... }
or end your foreach ():
and if ():
statements with the correct block endings:
$sqlRome="SELECT distinct id_jeune FROM jeunes_rome WHERE code_rome IN (";
// ^ no concatenation here
foreach ($liste_rome as $rome):
$sqlRome.="'".$rome."'";//HERE
if ($j < count($liste_rome) - 1):
$sqlRome.=",";
// end the if statement
endif;
// end the foreach loop
endforeach;
$sqlRome.=") GROUP BY id_jeune HAVING COUNT(*)=" . $j;
And where does $j
come from? As it does not change in the loop, it is either always adding a comma or never. That is probably not what you want.
Upvotes: 1
Reputation: 31739
Try with -
$sqlRome.="SELECT distinct id_jeune FROM jeunes_rome WHERE code_rome IN (";
foreach ($liste_rome as $rome) {
$var[] = "'".$rome."'";
}
$sqlRome.= implode(',', $var);
$sqlRome.=") GROUP BY id_jeune HAVING COUNT(*)=" . $j;
Upvotes: 0