doublestar2014 2017-05-21 07:27
浏览 33
已采纳

带有PDO样式连接的php购物车页面中的未定义索引

I trying to create a shopping cart using SESSION with PDO style connection, but I'm facing error

"Notice: Undefined index: name in" "Notice: Undefined index: price in"

I'm pretty sure that exists in my database table, here is the code

<?php  
    $stmt = $conn->prepare('SELECT * from tbl_product');
    $stmt->execute();
    if($stmt->fetchColumn() > 0) 
    {
        while($row = $stmt->fetchAll(PDO::FETCH_ASSOC))  
        {
        ?>  
        <div class="col-md-4">  
            <form method="post" action="../ppuyakul/cata_main?action=add&id=<?php echo $row["id"]; ?>">  
                <div style="border:1px solid #333; background-color:#f1f1f1; border-radius:5px; padding:16px;" align="center">  
                    <img src="<?php echo $row["image"]; ?>" class="img-responsive" /><br />  
                    <h4 class="text-info"><?php echo $row["name"] ?></h4>
                    <h4 class="text-danger">$ <?php echo $row["price"]; ?></h4>
                    <input type="text" name="quantity" class="form-control" value="1" />
                    <input type="hidden" name="hidden_name" value="<?php echo $row["name"]; ?>" />
                    <input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>" />
                    <input type="submit" name="add_to_cart" style="margin-top:5px;" class="btn btn-success" value="Add to Cart" />  
                </div>  
            </form>  
        </div>  
        <?php  
        }  

Thanks in advance, i really don't know how to solve this issue =(

  • 写回答

3条回答 默认 最新

  • douweng7308 2017-05-21 07:38
    关注

    The issue is with the function fetchAll which returns all the rows at once. You need to fetch the row one by one which can be done via fetch_row method of mysqli. You should change it from

    while($row = $stmt->fetchAll(PDO::FETCH_ASSOC))

    to

    while($row = $stmt->fetch_row(PDO::FETCH_ASSOC))

    Alternatively, You can also use fetchAll but then you need to store the results in a variable & then loop over that variable like below

    $all_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach($all_rows as $row)
    {
         //do the html part & anything
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据