0

I have a problem in sql query. I have to execute sql query in while loop.Below are my program

<?php
    $database = new Database();
    $db = $database->getConnection();
    $query = $db->query("Select * from cart");
    $query->execute();
    while($cd = $query->fetch(PDO::FETCH_ASSOC)){
?> 
<ul class="header-cart-wrapitem">
    <li class="header-cart-item">
        <div class="header-cart-item-img">
            <img src="images/item-cart-01.jpg" alt="IMG">
        </div>

        <div class="header-cart-item-txt">
            <a href="#" class="header-cart-item-name"><?php 
            $aa = $cd['cat'];
            $ab = $cd['id2'];

            $query = $db->query("Select * from $aa where id = $ab ");
            $query->execute();
            $cdd1 = $query->fetch(PDO::FETCH_ASSOC);
            echo $cd2 = $cdd1['detail'];
        ?></a>

        <span class="header-cart-item-info">
            <?php echo $cd['num'] ?> x 123
        </span>
    </div>
    </li>
</ul>
<?php 
    } 
?>

My second sql runs based on first sql.

My problem I am getting only one row means it is executing only once.

What I need I need all row.

0

2 Answers 2

2

You're reusing the $query variable inside the loop. So when the loop repeats and does

while($cd = $query->fetch(PDO::FETCH_ASSOC))

it's now fetching from the second query, not the original one.

Use a different variable inside the loop.

    $query2 = $db->query("Select * from $aa where id = $ab ");
    $query2->execute();
    $cdd1 = $query2->fetch(PDO::FETCH_ASSOC);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir you save my time.
0

You redefining $query inside of while scope. Yous use another variable (e.g. $query2 ) inside of the scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.