PHP & MySQL looping problem
I'm trying to loop once with the $cat_id
to grab its id
and category
values for the $url
value and then add the id
and category
values to the $parent_cat_id
and $sub_cat_name
arrays and then loop the $parent_cat_id
value just added to the array to find its id
and category
values and add them to the arrays until all the $url
values have been looped. But I can o开发者_如何学JAVAnly get the first $url
value to loop and not the rest of the $url
values to loop can someone help me correct this problem?
PHP code.
$parent_cat_id = array();
$sub_cat_name = array();
$cat_id = 23;
for ($i = 1; isset($_GET['sub'.$i]); ++$i) {
$url[$i] = '&sub' . $i . '=' . $_GET['sub'.$i];
if(isset($cat_id)){
$dbc = mysqli_query($mysqli, "SELECT id, category FROM categories WHERE url = '" . $url[$i] . "' AND parent_id = '" . $cat_id . "'");
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
$parent_cat_id[] = $row['id'];
$sub_cat_name[] = $row['category'];
}
}
} else {
$dbc = mysqli_query($mysqli, "SELECT id, category FROM categories WHERE url = '" . $url[$i] . "' AND parent_id = '" . $parent_cat_id[$i] . "'");
if (!$dbc) {
print mysqli_error($mysqli);
} else {
while($row = mysqli_fetch_array($dbc)){
$parent_cat_id[] = $row['id'];
$sub_cat_name[] = $row['category'];
}
}
}
}
Current output.
$parent_cat_id Array ( [0] => 77 )
$sub_cat_name Array ( [0] => A1 )
Expected Output.
$parent_cat_id Array ( [0] => 77 [1] => 78 [2] => 97 [3] => 100 )
$sub_cat_name Array ( [0] => A1 [1] => A2 [2] => B4 [3] => CD )
If I understand the problem correctly, you're basically saying that the loop runs only once but you want it to run multiple times.
However, check out the code below (simplified from yours). For clarity I've removed most of the loop's contents so you can see what's actually happening...
<?php
$_GET=array('sub1'=>'val_sub1','sub2'=>'val_sub2','sub3'=>'val_sub3','sub4'=>'val_sub4');
print_r($_GET);
/*
Array
(
[sub1] => val_sub1
[sub2] => val_sub2
[sub3] => val_sub3
[sub4] => val_sub4
)
*/
$url=array();
for ($i = 1;isset($_GET['sub'.$i]); $i++) {
$url[$i] = '&sub' . $i . '=' . $_GET['sub'.$i];
}
print_r($url);
/*
Array
(
[1] => &sub1=val_sub1
[2] => &sub2=val_sub2
[3] => &sub3=val_sub3
[4] => &sub4=val_sub4
)
*/
?>
As you can see, the loop works fine. So either...
the problem you're experiencing is because something's going horribly wrong with the database stuff and your script is just crashing after one loop (unlikely), or
the $_GET parameter only has one 'sub' value so it actually should just be looping once (likely), or
Maybe I just don't understand your question as well as I think I do.
精彩评论