如何将此代码从mysqli更改为PDO
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将此代码从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);
?>
我需要将此代码更改为PDO格式。而且我不确定PDO中mysqli_fetch_array的功能是什么。
答案
这是你怎么做的:
// 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>";
}
我用一个准备好的语句替换你的连接查询,你应该总是这样做!
关于获取:您可以逐个遍历记录,或者像我在数组中获取所有记录一样,并在其上获取foreach
。有很多不同的方法可以做到这一点。永远记住许多可用的PDO提取选项:https://phpdelusions.net/pdo#fetchall
以上是关于如何将此代码从mysqli更改为PDO的主要内容,如果未能解决你的问题,请参考以下文章
将 mysql 更改为 mysqli 及其 xampp 版本
如果内容不存在,如何将此代码更改为 INSERT 而不是 UPDATE? [复制]