doumixiang2227 2019-04-14 10:20
浏览 127
已采纳

如何将此代码从mysqli更改为PDO

if (isset($_GET['page_no']) && $_GET['page_no']!="") {
    $page_no = $_GET['page_no'];
    } else {
        $page_no = 1;
        }

    $total_records_per_page = 9;
    $offset = ($page_no-1) * $total_records_per_page;
    $previous_page = $page_no - 1;
    $next_page = $page_no + 1;
    $adjacents = "2"; 

    $result_count = mysqli_query($con,"SELECT COUNT(*) As total_records FROM `products`");
    $total_records = mysqli_fetch_array($result_count);
    $total_records = $total_records['total_records'];
    $total_no_of_pages = ceil($total_records / $total_records_per_page);
    $second_last = $total_no_of_pages - 1; // total page minus 1

    $result = mysqli_query($con,"SELECT * FROM `products` LIMIT $offset, $total_records_per_page");
    while($row = mysqli_fetch_array($result)){
        echo "<tr>
              <td>".$row['productCode']."</td>
              <td>".$row['productName']."</td>
              <td>".$row['MSRP']."</td>
              <td><button type='submit' class='buy'>Buy Now</button></td>
              </tr>";
        }
    mysqli_close($con);
    ?>

I need to change this code to PDO format. And I am not really sure what is the same function of mysqli_fetch_array in PDO.

  • 写回答

1条回答 默认 最新

  • dptt66700 2019-04-14 11:53
    关注

    This is how you would do it:

    // Execute query and fetch a single cell from the result
    $total_records = $PDO->query('SELECT COUNT(*) FROM `products`')->fetch(PDO::FETCH_COLUMN);
    
    $total_no_of_pages = ceil($total_records / $total_records_per_page);
    $second_last = $total_no_of_pages - 1; // total page minus 1
    
    // prepare a statement with 2 parameters and execute it
    $stmt = $PDO->prepare('SELECT * FROM `products` LIMIT ?,?');
    $stmt->execute([$offset, $total_records_per_page]);
    // PDO results are easily traversable
    foreach ($stmt->fetchAll() as $row) {
        echo "<tr>
            <td>".$row['productCode']."</td>
            <td>".$row['productName']."</td>
            <td>".$row['MSRP']."</td>
            <td><button type='submit' class='buy'>Buy Now</button></td>
            </tr>";
    }
    

    I replaced your concatenated query with a prepared statement, which you should always do!

    About fetching: You can traverse the records one by one or fetch all of them like I did into an array and foreach on them. There is many different ways to do it. Always remember about many PDO fetch options available: https://phpdelusions.net/pdo#fetchall

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分