【发布时间】:2015-08-21 00:53:25
【问题描述】:
我正在尝试在 PHP 上创建一个购物车,但它不起作用,页面不会显示任何东西,我已经查看了我的代码,甚至重做了它,但它根本不起作用。 ..如果有人可以帮助我,那就太好了,我会尽力解释我的逻辑。
<?php
session_start(); // I use sessions!
include('librerias/conexion.php'); // This calls the DB connection which is ok!
if (isset($_SESSION['carrito'])){ //If the shopping cart is set...
$arreglo=$_SESSION['carrito']; //an array will be set on the session variable
$encontro=false; //this is a flag to see if the added item is already on the cart
$numero = 0; // This will be used for index on the array
for($i=0; $i<count($arreglo); $i++){ // This loop searchs the array to see if there's a matching ID, if there is, then the quantity goes up by one
if($arreglo[$i]['Id']==$_GET['id']){
$numero=$i;
$encontro=true;
}
if($encontro){
$arreglo[$numero]['cantidad']+=1;
}
}
}else{ //If there's no session shopping cart...
if(isset($_GET['id'])){ //it will check if it comes with an id from an item
$nombre="";
$precio="";
$id = $_GET['id'];
$sql="SELECT * FROM productos WHERE id=$id"; // This is my query to get data from that item
print $sql;
$res= mysql_query($sql); //Query...
print $res;
while($fila= mysql_fetch_array($res)){ //This will set the name of the item, the price, and the image
$nombre=$fila['nombre'];
$precio=$fila['precio'];
$imagen = $fila['imagen'];
}
$arreglo[]= array('Id'=>$id, //when all that is set, this array is created with all those values
'Nombre'=>$nombre,
'precio'=>$precio,
'imagen'=>$imagen,
'cantidad'=>1);
$_SESSION['carrito']=$arreglo; // Finally the Session shopping cart s set to be the array
}
}
?>
<?php
include("librerias/header.php");
?>
<?php if(isset($_SESSION['carrito'])){ //Now it checks if it's set again and creates a table
$total=0;
?>
<table class="table"><th>Nombre</th><th>Precio</th><th>Imagen</th><th>Cantidad</th><th>Subtotal</th></table>
<?php
for($i=0; $i<count($_SESSION['carrito']); $i++){
?>
<tr>
<td><?php echo $_SESSION['carrito']['Nombre'];?></td>
<td><?php echo $_SESSION['carrito']['precio'];?></td>
<td><img src=" <?php echo $_SESSION['carrito']['imagen'];?>"</td>
<td><?php echo $_SESSION['carrito']['cantidad'];?></td>
<td><?php echo $_SESSION['carrito']['precio']*$_SESSION['carrito']['cantidad'];?></td>
</tr>
<?php
}
}else{
echo "<center>El carrito está vacío</center>";
}
?>
<?php
include("librerias/footer.php");
?>
完成..
但我的结果是:
注意:未定义索引:C:\xampp\htdocs\TiendaJavier\carrito.php 第 52 行中的 Nombre
注意:未定义索引:第 53 行 C:\xampp\htdocs\TiendaJavier\carrito.php 中的 precio
注意:未定义索引:C:\xampp\htdocs\TiendaJavier\carrito.php 第 55 行中的候选对象
注意:未定义索引:第 56 行 C:\xampp\htdocs\TiendaJavier\carrito.php 中的 precio
注意:未定义索引:C:\xampp\htdocs\TiendaJavier\carrito.php 第 56 行中的候选对象
我真的无法解决问题...提前谢谢
【问题讨论】:
-
$_session 不包含那些索引....你还没有设置它们,我说你的 if $_SESSION['carrito'] 是真的,但里面没有数据?
-
其实我看到 $arreglo[]= array() 意味着你访问 $arreglo[0][key] 等等