gpt4 book ai didi

php - 将 mysql_fetch_array 更改为等效的 PDO

转载 作者:行者123 更新时间:2023-11-29 03:26:45 25 4
gpt4 key购买 nike

<?php

$sql="SELECT * FROM products WHERE id_product IN (";

foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}

$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query=mysql_query($sql);
$totalprice=0;

while ($row=mysql_fetch_array($query)){
$subtotal=$_SESSION['cart'][$row['id_product']]['quantity']*$row['price'];
$totalprice+=$subtotal;
?>
<tr>
<td><?php echo $row['name'] ?></td>
<td><input type="text" name="quantity[<?php echo $row['id_product'] ?>]" size="5" value="<?php echo $_SESSION['cart'][$row['id_product']]['quantity'] ?>" /></td>
<td><?php echo $row['price'] ?>$</td>
<td><?php echo $_SESSION['cart'][$row['id_product']]['quantity']*$row['price'] ?>$</td>
</tr>
<?php
}
?>
<tr>
<td>Total Price: <?php echo $totalprice ?></td>
</tr>

这是我目前使用的代码。我得到的明显错误是:

Fatal error: Uncaught Error: Call to undefined function mysql_query()

我知道我需要将它更改为 PDO,但我不确定用什么替换 mysql_fetch_array,同时仍能获得我想要的总价。
改成这样后:

foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}

$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$stmt = $db->prepare($sql);
$stmt->execute();
$totalprice=0;

我不确定如何在获得正确的总价的同时继续进行

最佳答案

$sql="SELECT * FROM products WHERE id_product IN (";

foreach($_SESSION['cart'] as $id => $value) {
$sql.=$id.",";
}

$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$stmt = $db->prepare($sql);
$stmt->execute();
$totalprice=0;

$result = $stmt->fetchAll(PDO::FETCH_ASSOC); # FOr mysql_fetch_assoc

foreach ($result as $index=>$arr) {
// $val = $arr['key'];
}

纯mysql方式:

while ($row =  $stmt->fetch(PDO::FETCH_ASSOC) {
// $val = $row['key'];
}

对于 mysql_fetch__array:

您可以使用 PDO::FETCH_NUM

链接:http://php.net/manual/en/pdostatement.fetchall.php

http://micmap.org/php-by-example/manual/de/pdostatement.fetch.html

关于php - 将 mysql_fetch_array 更改为等效的 PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34927545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com