php - 将 session 变量插入 MySQL

标签 php mysql debugging session-variables

我的 PHP 代码有问题。我正在尝试使用 session 变量信息将数据插入到 mysql 数据库中。与 SQL 表的连接正常。每当我提交表单时,它都不会显示任何 session 变量。代码相当长。任何帮助将不胜感激。

查看购物车页面

<h1 align="center">View Cart</h1>
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%"  cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
  <tbody>
    <?php
    if(isset($_SESSION["cart_products"])) //check session var
    {
        $total = 0; //set initial total value
        $b = 0; //var for zebra stripe table 
        foreach ($_SESSION["cart_products"] as $cart_itm)
        {
            //set variables to use in content below
            $product_name = $cart_itm["product_name"];
            $product_qty = $cart_itm["product_qty"];
            $product_price = $cart_itm["product_price"];
            $product_code = $cart_itm["product_code"];
            $product_color = $cart_itm["product_color"];
            $subtotal = ($product_price * $product_qty); //calculate Price x Qty




            $bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe 
            echo '<tr class="'.$bg_color.'">';
            echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
            echo '<td>'.$product_name.'</td>';
            echo '<td>'.$currency.$product_price.'</td>';
            echo '<td>'.$currency.$subtotal.'</td>';
            echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
            echo '</tr>';
            $total = ($total + $subtotal); //add subtotal to total var
        } 

        $grand_total = $total + $shipping_cost; //grand total including shipping cost
        foreach($taxes as $key => $value){ //list and calculate all taxes in array
                $tax_amount     = round($total * ($value / 100));
                $tax_item[$key] = $tax_amount;
                $grand_total    = $grand_total + $tax_amount;  //add tax val to grand total
        }

        $list_tax       = '';
        foreach($tax_item as $key => $value){ //List all taxes
            $list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
        }
        $shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
    }
    ?>
    <tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : R <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
    <tr><td colspan="5"><a href="Windex.php" class="button">Add More Items</a><button type="submit">Update</button></td></tr>

  </tbody>
</table>
<input type="hidden" name="return_url" value="<?php 
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>



</form>

</form>

购物车更新页面

<?php
session_start();
include_once("config.php");

//add product to session or create new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
    foreach($_POST as $key => $value){ //add all post vars to new_product array
        $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
    }
    //remove unecessary vars
    unset($new_product['type']);
    unset($new_product['return_url']); 

    //we need to get product name and price from database.
    $statement = $mysqli->prepare("SELECT product_name, price FROM products WHERE product_code=? LIMIT 1");
    $statement->bind_param('s', $new_product['product_code']);
    $statement->execute();
    $statement->bind_result($product_name, $price);

    while($statement->fetch()){

        //fetch product name, price from db and add to new_product array
        $new_product["product_name"] = $product_name; 
        $new_product["product_price"] = $price;

        if(isset($_SESSION["cart_products"])){  //if session var already exist
            if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array
            {
                unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item
            }           
        }
        $_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item  
    } 
}


//update or remove items 
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
    //update item quantity in product session
    if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
        foreach($_POST["product_qty"] as $key => $value){
            if(is_numeric($value)){
                $_SESSION["cart_products"][$key]["product_qty"] = $value;
            }
        }
    }
    //remove an item from product session
    if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
        foreach($_POST["remove_code"] as $key){
            unset($_SESSION["cart_products"][$key]);
        }   
    }
}

//back to return url
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url
header('Location:'.$return_url);

?>

我遇到问题的页面,Insert Variables.php

<?
$product_name = $_SESSION["product_name"];
            $product_qty = $_SESSION["product_qty"];
            $product_price = $_SESSION["product_price"];


$hostname="Localhost";
$username="ABCD"; 
$password="";
$dbname="Abc"; 
$usertable="Shop"; 

$link = mysqli_connect($hostname,$username,$password,$dbname);


if(isset($_POST['submit'])){ 
$product_name = $_SESSION["product_name"];
            $product_qty = $_SESSION["product_qty"];
            $product_price = $_SESSION["product_price"];
}


if($link === false) {
    die("Error: Could not connect.".mysqli_connect_error());
}

$sql = "INSERT INTO $usertable (Qty, product,productID) VALUES ('{$_SESSION['product_qty']}', '{$_SESSION['product_name']}', '{$_SESSION['cart_products']}')";

if (mysqli_query($link, $sql)){

    echo "<h1> Succes </h1>";
} else {
    echo "Error: could not execute $sql. " . mysqli_error($link);
}

mysqli_close($link);
?>

最佳答案

我猜问题出在 Variables.php 的最开始处 你有:

$product_name = $_SESSION["product_name"];
$product_qty = $_SESSION["product_qty"];
$product_price = $_SESSION["product_price"];

但是,它应该是:

$product_name = $_SESSION["cart_products"][$key]["product_name"];
$product_qty = $_SESSION["cart_products"][$key]["product_qty"];
$product_price = $_SESSION["cart_products"][$key]["product_price"];

其中 $key 是产品代码 然后使用变量

$sql = "INSERT INTO $usertable (Qty, product, productID) VALUES ('$product_qty', '$product_name', '$key'";

关于php - 将 session 变量插入 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52911363/

相关文章:

javascript - 基于load()停止运行javascript

php - PHP-MySQL 分页中的序列号

c - 使用定义结构的 C 头文件解析数据

visual-studio - 使用断点条件进行调试时,Visual Studio 行为异常

php - 将 PHP 代码添加到 Drupal 7 页面

php - MySQL 获取 LIKE 和多页搜索的起始编号

php - 从表中查找所有 NULL 值

javascript - 使用 Ajax、JavaScript 和 HTML 发布一些数据

mysql - 尝试安装 Perl-Mysql DBD,找不到 mysql_config

mysql - 如何在不中断应用程序控制流的情况下调试 MySql 存储过程