【发布时间】:2014-07-05 23:53:25
【问题描述】:
我真的很难用脚本从会话数组中提取值,然后从我的数据库中的表中调用信息。
我可以将值存储在会话中没有问题,当我打印它时它看起来像这样:
数组([0] => 17 [1] => 18 [2] => 19 [3] => 20 [4] => 20 [5] => 19 [6] => 17)
然后我有下面的 PHP 从数组中提取值并从我的数据库中提取记录,但它似乎在某个地方中断了,不幸的是我仍然是 PHP 的菜鸟。
?php
$action = isset($_GET['action']) ? $_GET['action'] : "";
if($action=='removed'){
echo "<div> was removed from cart.</div>";
}
if(isset($_SESSION['cart'])){
$ids = "";
foreach($_SESSION['cart'] as $id){
$ids = $ids . $id . ",";
}
// remove the last comma
$ids = rtrim($ids, ',');
$query = "SELECT * FROM events WHERE EventID IN ({$ids})";
$stmt = $con->prepare( $query );
$stmt->execute();
$num = $stmt->rowCount();
if($num>0){
echo "<table border='0'>";//start table
// our table heading
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price</th>";
echo "<th>Action</th>";
echo "</tr>";
//also compute for total price
$totalPrice = 0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$totalPrice += $EventCost;
//creating new table row per record
echo "<tr>";
echo "<td>{$EventID}</td>";
echo "<td class='textAlignRight'>{$EventCost}</td>";
echo "<td class='textAlignCenter'>";
echo "<a href='removeFromCart.php?id={$EventID} class='customButton'>";
echo "<img src='images/remove-from-cart.png' title='Remove from cart' />";
echo "</a>";
echo "</td>";
echo "</tr>";
}
echo "<tr>";
echo "<th class='textAlignCenter'>Total Price</th>";
echo "<th class='textAlignRight'>{$totalPrice}</th>";
echo "<th></th>";
echo "</tr>";
echo "</table>";
echo "<br /><div><a href='#' class='customButton'>Checkout</a></div>";
}else{
echo "<div>No products found in your cart. :(</div>";
}
}else{
echo "<div>No products in cart yet.</div>";
}
?>
我假设它打破了查询,但我对此仍然很陌生。
我正在尝试提取表中的所有字段,但我尝试链接到的主键称为“EventID”。数组中的 ID 确实与我试图提取的记录匹配。
我从另一个教程网站复制了这段代码,这就是为什么我很难将它与我自己的匹配。
提前感谢您的帮助。
【问题讨论】:
-
foreach($_SESSION['cart'] as $k=>$id){ $ids = $ids . $id . ","; } -
你在任何地方都没有
session_start()...另外,你的整个$ids循环毫无意义:$ids = implode(',' $_SESSION['cart']))会更有效地做同样的事情。
标签: php mysql arrays session foreach