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

如何将此代码从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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀