PHP While Foreach of MySQL key

179 views Asked by At

Search far and wide and couldn't find an answer so I thought it was time to post. I currently have a table of vendors. I would like to loop through each vendor using the 'skuid' value for each as it is unique, then echo other information from that row. Here's what I have so far.

$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ($mysqli->connect_errno) {
    echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
    exit();
}

$vendorQuery = "SELECT skuid FROM vendors";
$vendorResult = mysqli_query($mysqli, $vendorQuery);

while($row = mysqli_fetch_assoc($vendorResult)) {
    foreach($row['skuid'] as $vendorid) {
        echo $row['skuid'];
    }
} ?>
1

There are 1 answers

1
Hanky Panky On

You don't need that foreach, your outer loop is enough

while($row = mysqli_fetch_assoc($vendorResult)) {
        echo $row['skuid'];
}

And a single mysql query doesn't return nested levels of data so there can't be any good use cases for a nested loop in this scenario.

When this loop runs, there is always only 1 skuid per row. There is no use for another nested loop there.

Now if you want to create an array of vendors from this query and then loop over it that's a good use case. For example

while($row = mysqli_fetch_assoc($vendorResult)) {
        $skuid=$row['skuid'];
        $name=$row['name'];
        $vendors[$skuid]=array('name'=>$name); // and other fields
}
foreach($vendors as $vendor){
        echo $vendor['name'];
}