亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將數組數據推入會話時出錯

將數組數據推入會話時出錯

PHP
Cats萌萌 2023-10-22 22:01:53
我有一個 php 代碼將產品添加到會話中,但它沒有按預期工作,下面是我的代碼:<?phpsession_start();include 'db.php';$status = 1;if (isset($_POST['id']) && $_POST['id']!=""){    $id = $_POST['id'];    $sql = "SELECT * FROM website_tree WHERE id = '$id' ";    $result = mysqli_query($link, $sql);    $row = mysqli_fetch_array($result);    $id = $row['id'];    $name = $row['name'];    $price = $row['price'];    $image = $row['image'];    $cartArray = array(        'id'=>$id,        'name'=>$name,        'price'=>$price,        'image'=>$image,        'quantity'=>1    );    if(empty($_SESSION["shopping_cart"]['product'])) {        $_SESSION["shopping_cart"]['product'] = array_push($_SESSION["shopping_cart"], $cartArray);        $status = 1;    }else{        $_SESSION["shopping_cart"]['product'] = array_push($_SESSION["shopping_cart"], $cartArray);        $status = 1;    }}echo json_encode(array("status"=>$status)); ?>我收到這個警告: array_push() expects parameter 1 to be array, null誰能幫我糾正我的代碼?
查看完整描述

2 回答

?
達令說

TA貢獻1821條經驗 獲得超6個贊

$_SESSION["shopping_cart"]['product']如果未定義(未設置)則定義。


session_start();

include 'db.php';

$status = 1;

// here

if (!isset($_SESSION["shopping_cart"]['product'])) {

    $_SESSION["shopping_cart"]['product'] = [];

}


// more code here...



$cartArray = array(

    'id'=>$id,

    'name'=>$name,

    'price'=>$price,

    'image'=>$image,

    'quantity'=>1

);


// `array_push` works with array by reference

// so there's no need to reassign this variable

array_push($_SESSION["shopping_cart"]['product'], $cartArray);

$status = 1;


查看完整回答
反對 回復 2023-10-22
?
嚕嚕噠

TA貢獻1784條經驗 獲得超7個贊

您的代碼看起來不錯,但您需要將 session_start() 放在 <?php 標記之后。

確保此函數之前沒有任何輸出(甚至是空格符號等)。

所以改變:

<?php
session_start();

到:

<?php session_start();


查看完整回答
反對 回復 2023-10-22
  • 2 回答
  • 0 關注
  • 151 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號