繁体   English   中英

如何将HTML中的变量插入数组PHP并将数组PHP显示回HTML?

[英]How to insert variable from HTML into array PHP and display array PHP back to HTML?

我在PHP中使用的数组名称为$ OrderHistory。我尝试使每当客户单击“ AddtoCart”按钮并将其显示回HTML表单时自动将其插入到PHP数组中,但这似乎不起作用。 任何帮助都感激不尽。

假设有来自HTML的变量,我要获取它并将其放置在数组php中,名为$ _POST ['menu']和$ _POST ['Quantity'];

if(isset($_POST['AddCart'])){
    if($_POST['menu']!= 0){

        if($_POST['Quantity'] != 0){
            $MName = $_POST['menu'];
            $MQuantity = $_POST['Quantity'];
            $OrderHistory = array($No => // $No Refers to number of order that customer made
                                        array(
                                         $Order => $MName,$MQuantity));

        }
    }
    $Count++; // $Count and $No are key that will show where the next menu and quantity goes in array.
    $No++;   
}

在这下面,我将向客户显示已插入的数组PHP到HTML内的数据。我尝试了多种方法,但仅显示键数和数量。

    <td align=center><?=    ;?></td> // this will be display number of key array in php
    <td align=center><?=    ;?></td> // this will be display name of food
    <td align=center><?=    ;?></td> // this will be display quantity of food

您可以执行以下操作。 我在这里使用GET方法,如果愿意,可以使用POST方法。

<?php
// start session 
session_start();

// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : 1;

// make quantity a minimum of 1
$quantity=$quantity<=0 ? 1 : $quantity;

// add new item on array
$cart_item=array(
    'quantity'=>$quantity
);

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(!isset($_SESSION['cart'])){
    $_SESSION['cart'] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart'])){
    // redirect to product list and tell the user it was added to cart
}

// else, add the item to the array
else{
    $_SESSION['cart'][$id]=$cart_item;

    // redirect to product list and tell the user it was added to cart
}
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM