mardi 18 octobre 2016

I am trying to concatenate checkboxes into an SQL statement in PHP

I have a very simple HTML form with POST method sending the name of certain activities which are checked or not...

<input type="checkbox" name="games[]" value="darts=1">Darts</input>
<input type="checkbox" name="games[]" value="e-darts=1">e-Darts</input>
<input type="checkbox" name="games[]" value="pool=1">Pool</input>
<input type="checkbox" name="games[]" value="snooker=1">Snooker</input>
<input type="checkbox" name="games[]" value="airhockey=1">Air Hockey</input>
<input type="checkbox" name="games[]" value="quizmachine=1">Quiz Machine</input>
<input type="checkbox" name="games[]" value="food=1">Food</input></br></br>

This isn't the problem, i'm getting the values through, all hunky dory.

I'm then trying to take from the array any checked values in a foreach loop and concatenate the values into the where clause by adding " and " in between all until the last one. However, they are not concatenating and just outputting the final checkbox result - how can I concatenate? This is my php code:

$i = 0;
if(!empty($_POST['games'])) {
foreach($_POST['games'] as $check)  {
    if(++$i === count($_POST['games']))     {
/*echo $check;*/
}
else    {
$check = $check . " and ";
/*echo $check;*/
}
}
}


try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,         $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach($conn->query("SELECT * from Establishments where town like '".$publocation."' and ".$check."") as $row) {
    print $row['name'] . "</br>";

}
$conn = null;
} 
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}




Aucun commentaire:

Enregistrer un commentaire