变量被添加到从另一个页面传递的 session 数组
此处为详细信息页面
<?php
session_start();
require_once 'core/init.php';
include 'includes/header.php';
include 'includes/navigation.php';
// cart code
if(empty($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
array_push($_SESSION['cart'], $_GET['id']);
这里是购物车页面
这是一些示例产品的输出
array(5) { [0]=> string(4) "3911" [1]=> string(4) "5005" [2]=> NULL [3]=> string(4) "3393" [4]=> string(3) "185" }
和当前的 SQL 查询
SELECT * FROM `wheels` WHERE `recid` LIKE (3911, 5005, , 3393, 185)
所以我知道数组正在正确获取值(排除空值)
session_start();
require_once 'core/init.php';
include 'includes/header.php';
var_dump($_SESSION['cart']);
$whereIn = implode(', ', $_SESSION['cart']);
// fetching products for cart
$cartQuery = "SELECT * FROM `wheels` WHERE `recid` = ($whereIn)";
$cartResult = mysqli_query($db, $cartQuery);
echo $cartQuery;
当尝试使用
调用 Sql 结果时 <?php while($product = mysqli_fetch_assoc($cartResult)) : ?>
我收到错误
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in (blah blah directory) on line 121
从数组中过滤空值的最佳实践是什么?例如。该数组不会传递空值(当他们单击购物篮按钮时发生)。
有人可以解释为什么 while 循环无法得到结果吗?我假设这是因为 mysql 查询没有将结果返回到结果变量?如果是这样,应该使用什么语法将 $_SESSION 传递到查询中以获得多个结果?
抱歉问了这么多问题。
最佳答案
您不能运行这样的查询:
SELECT * FROM `wheels` WHERE `recid` LIKE (3911, 5005, , 3393, 185)
您应该删除空节点并使用 IN 而不是:
SELECT * FROM `wheels` WHERE `recid` IN(3911, 5005, 3393, 185)
删除空元素:
$newArray =array();
foreach($array as $key => $value)
{
if($value != null)
$newArray[] = $value;
}
print_r($newArray);
关于PHP session 购物车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37404198/