【问题标题】:PHP Sessions Shopping CartPHP 会话购物车
【发布时间】:2016-05-24 04:04:58
【问题描述】:

变量被添加到从另一个页面传递的会话数组中

详情页在这里

<?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)

所以我知道数组正确获取值(禁止 null)

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 传递到查询中以获得多个结果?

很抱歉问了这么多问题。

【问题讨论】:

    标签: php mysql arrays session


    【解决方案1】:

    您不能运行这样的查询:

    SELECT * FROM `wheels` WHERE `recid` LIKE (3911, 5005, , 3393, 185)
    

    您应该删除空节点并使用 IN 而不是 like:

    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);
    

    【讨论】:

    • 如何删除空节点?
    • 您可以遍历数组中的每个值并检查其值是否为空,如果它为空,则在您的查询中没有使用它
    【解决方案2】:

    在您的 SQL 查询 "SELECT * FROM wheels WHERE recid = ($whereIn)" 中,您使用了 = 而不是 LIKE。请检查。还要检查一次 $cartQuery 你回应了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      相关资源
      最近更新 更多