santyas
santyas

Reputation: 96

foreach inside while loop not work

Im trying to display a list of cars with specifications: weight, length, width.
Everything would be inside a foreach and inside a while, but I cant run it properly...

My tables
cars:
idcar: 1 / width:30 / length:10 / weight:300
idcar: 2 / width:20 / length:12 / weight:210
idcar: 3 / width:20 / length:21 / weight:230
idcar: 4 / width:40 / length:11 / weight:210

and specs table:
idspec:1 spec:width
idspec:2 spec:weight
idspec:3 spec:length

And my code

$idcar = $_GET['idcar'];
$resultcarfirst = mysqli_query($connecDB,"select * from products order by (case idcar when $idcar then 0 else idcar end), $idcar asc");
$resultspec = mysqli_query($connecDB, "SELECT * FROM specs ORDER BY idspec");

while($rowspec = mysqli_fetch_array($resultspec)){
        echo '<div><h1>'.$rowspec["spec"].'</h1><br/>';

        $arraycars = array();
        while($rowcar = mysqli_fetch_array($resultcarfirst))
        $arraycars[] = $rowcar;
        foreach($arraycars as $rowcar){
            echo '<p>idcar:'.$rowcar['idcar'].' '.$rowspec['spec'].': '.$rowcar[$rowspec['spec']].'</p>';
        }

        echo '</div><br/>';
    }

The output would be:
Width
idcar:1 width:30
idcar:2 width:20
idcar:3 width:20
idcar:4 width:40

Weight
idcar:1 weight:300
idcar:2 weight:210
idcar:3 weight:230
idcar:4 weight:210

Length
idcar:1 length:10
idcar:2 length:12
idcar:3 length:21
idcar:4 length:11

Thank you and i hope I was clear.

Upvotes: 0

Views: 292

Answers (1)

Kylie
Kylie

Reputation: 11749

WHy would you do this..??

All you need is...

    $arraycars = array();
    while($rowcar = mysql_fetch_array($resultcarfirst)){
    echo '<p>idcar:'.$rowcar['idcar'].' '.$rowspec['name'].':    '.$rowcar[$rowspec['spec']].'</p>';
    $arraycars[] = $rowcar;}

Unless Im completely misunderstanding what you want to do.?

Also...if you wanna pull the sspecs only for that car....with that while loop, then you have to change your query to accept a variable from the first while loop, if you know what I mean

Upvotes: 2

Related Questions