Reputation: 2588
I am sending a variable with multiple values like this:
JQUERY:
$(".indexMain").load('indexMain.php?color=' + colors.join("+"), function()
--> indexMain.php?colors=blue+red+brown
I want to _GET those values and then use them in a while loop to put them into a SQL query like this one:
$items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 = :colorbase1");
$items -> bindValue(":colorbase1", $color);
Thanks!
EDIT: here is my current code but it is not working, it just shows the items corresponding to the 1st color.
foreach (explode(' ', $_GET['color']) as $color)
{
$items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 = :colorbase1");
$items -> bindValue(":colorbase1", $color);
}
Upvotes: 1
Views: 3360
Reputation: 12652
indexMain.php?color=blue+red+brown
should be
indexMain.php?colors%5B%5D=blue&colors%5B%5D=red&colors%5B%5D=brown
which is equivalent to
indexMain.php?colors[]=blue&colors[]=red&colors[]=brown
This creates an array accessible with $_GET['colors']
. After that use this PHP:
foreach ($_GET['colors'] as $color) {
$query = $con->prepare("SELECT * FROM item_descr WHERE color_base1 = :colorbase1");
if ($query->execute(":colorbase1", $color)) {
// use results from query
} else {
// handle failed query
}
}
If you don't want to change the query string, you can do this alternatively:
foreach (explode(' ', $_GET['colors']) as $color) {
$query = $con->prepare("SELECT * FROM item_descr WHERE color_base1 = :colorbase1");
if ($query->execute(":colorbase1", $color)) {
// use results from query
} else {
// handle failed query
}
}
Note that the only change is in the first line and we are splitting the string by spaces (because "+" gets converted to a space character).
Also note that both examples assume that $_GET['colors']
is defined. You can use isset()
to check if it is defined.
Upvotes: 3
Reputation: 4678
Try this
$colors = explode("+", $_GET['color']);
foreach($colors as $color){
$items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 = :colorbase1");
$items -> bindValue(":colorbase1", $color);
}
How about this
$colors = explode(" ", $_GET['color']);
foreach($colors as $color){
$items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 = :colorbase1");
$items -> bindValue(":colorbase1", $color);
}
Upvotes: 0
Reputation: 90432
I think this should work:
$colors = explode(' ', $_GET['color']);
foreach($colors as $color) {
// your code here...
}
Upvotes: 0