doumixiang2227
2019-04-14 10:20 阅读 93
已采纳

如何将此代码从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 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

    点赞 评论 复制链接分享

相关推荐