【问题标题】:Changing mysql_fetch_array to PDO equivalent将 mysql_fetch_array 更改为等效的 PDO
【发布时间】:2016-01-21 15:20:34
【问题描述】:
<?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>

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

致命错误:未捕获错误:调用未定义函数 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;

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

【问题讨论】:

  • mysql_* 功能已被删除,请查看php.net 上的PDOMySQLi
  • PDO mysql_fetch_array()$conn-&gt;fetchAll() 其中$conn 是连接变量。

标签: php mysql pdo


【解决方案1】:
$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

【讨论】:

  • 我收到错误:警告:为 foreach() 提供的参数无效在行:foreach($_SESSION['cart'] as $id =&gt; $value) {
  • 这是因为 $_SESSION['cart'] 应该是一个数组。不是数组吗?通过 echo gettype($_SESSION['cart']); 来检查 $_SESSION['cart'] 的类型;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-23
  • 2012-07-18
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多