linda111 Posted January 25, 2017 Share Posted January 25, 2017 i try to do while loop using fetchAll...but only 1st item will be the output. thanks for the help <?php function cart_display(){ global $db; $ip=getIp(); $query = $db->prepare(" SELECT * FROM cart where ip_add = '$ip'"); $query->setFetchMode(PDO::FETCH_ASSOC); $query->execute(); while ($row=$query->fetch()): $product_id=$row['p_id']; $query = $db->prepare("SELECT * FROM product where product_id = :product_id"); $query->bindParam(':product_id', $product_id); //$query->setFetchMode(PDO::FETCH_ASSOC); $rows = $query->fetchAll(PDO::FETCH_ASSOC); $query->execute(); $row=$query->fetch(); echo" <tr> <td><input type = 'checkbox' name='remove[]' value='<?php echo $product_id?>'/> </td> <td>".$row['product_name']." <br><img src='admin/product_images/".$row['product_image']."' width='80' height='80'/></td> <td><input type='text' name='qty' value='".$row['qty']."'/></td> <td>".$row['product_price']."</td> </tr> "; endwhile; ?> Quote Link to comment https://forums.phpfreaks.com/topic/303021-pdo-while-loop/ Share on other sites More sharing options...
Jacques1 Posted January 25, 2017 Share Posted January 25, 2017 (edited) The database code doesn't make much sense. You're using prepared statements (which is good), but then you're just inserting the input right into the query string. You call fetchAll(), ignore the result and then call fetch(). What is this supposed to do? You also keep overriding your variables everywhere. On top of that, running queries in a loop is very inefficient. You should learn some database basics before jumping to complex applications. Combining tables is done with joins. The point of prepared statements is to pass all input through parameters. You should pick one fetch method. And it helps a lot to have meaningful variable names. If all of them are called $query and $row, you're almost guaranteed to end up with collisions. <?php // make PDO::FETCH_ASSOC the default fetch mode instead of repeating it over and over again $product_stmt = $db->prepare(' SELECT product.product_id, product.product_name, product.product_price, product.product_image, cart.qty FROM cart JOIN product ON cart.p_id = product.product_id WHERE cart.ip_add = :ip '); $product_stmt->execute([ 'ip' => getIp(), ]); $products = $product_stmt->fetchAll(); And as multiple people have already told you, using the IP as a customer identifier is a major design error. It means that a customer may end up sharing “their” cart with hundreds or thousands of other people whom they don't even know. Edited January 25, 2017 by Jacques1 Quote Link to comment https://forums.phpfreaks.com/topic/303021-pdo-while-loop/#findComment-1541968 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.