【发布时间】:2014-04-11 00:13:06
【问题描述】:
刚刚进行了搜索,但找不到具有适当答案的问题。我正在尝试将 product_id 添加到数组的末尾,每次添加一些东西时,它也会添加到数组中。目前,每次我添加 product_id 时,它都会替换之前的任何内容。我得到的只是 Array[0] 处的一个 product_id。下面是我添加到数组中的代码部分。然后我使用
print_r($order);
显示数组中的内容。
$order = array();
switch ($action)
{
// Add
case "add":
$order[] = $product_id;
break;
}
这是页面中的完整代码减去一些 MySQL 内容。
include 'connection.php';
if (isset($_GET['action']))
{
$action = $_GET['action']; //Get's action from the URL
}
if (isset($_GET['product_id']))
{
$product_id = $_GET['product_id']; //the action from the URL
}
// if there is an product_id and that product_id doesn't exist display an error message
if ($product_id && !productExists($product_id))
{
die("Error. Product Doesn't Exist");
}
switch ($action)
{ //decide what to do
// Add
case "add":
$order[] = $product_id;
if (isset($_SESSION['user']))
{
$productadd = sprintf("INSERT INTO tbl_basket (customer_id, product_id, basket_status) VALUES ('" . $_SESSION['user'] . "','$product_id','basket')");
mysql_query($productadd);
break;
}
else
{
$productadd = sprintf("INSERT INTO tbl_basket (customer_id, product_id, basket_status, user_type) VALUES ('" . $_SESSION['guestuser'] . "','$product_id','basket', 'guest')");
mysql_query($productadd);
break;
}
// Remove
case "remove":
if (isset($_SESSION['user']))
{
$productremove = sprintf("DELETE FROM tbl_basket WHERE customer_id = '" . $_SESSION['user'] . "' AND product_id = '$product_id'");
mysql_query($productremove);
break;
}
else
{
$productremove = sprintf("DELETE FROM tbl_basket WHERE customer_id = '" . $_SESSION['guestuser'] . "' AND product_id = '$product_id'");
mysql_query($productremove);
break;
}
// Empty
case "empty":
if (isset($_SESSION['user']))
{
$empty = sprintf("DELETE FROM tbl_basket WHERE customer_id = '" . $_SESSION['user'] . "' AND order_status = 'basket'");
mysql_query($empty);
break;
}
else
{
$empty = sprintf("DELETE FROM tbl_basket WHERE customer_id = '" . $_SESSION['user'] . "' AND order_status = 'basket'");
mysql_query($empty);
break;
}
}
if (isset($_SESSION['user']))
{
$result = mysql_query("SELECT * FROM tbl_basket a INNER JOIN tbl_products b ON a.product_id = b.product_id WHERE a.customer_id = '" . $_SESSION['user'] . "'");
}
else
{
$result = mysql_query("SELECT * FROM tbl_basket a INNER JOIN tbl_products b ON a.product_id = b.product_id WHERE a.customer_id = '" . $_SESSION['guestuser'] . "'");
}
【问题讨论】:
-
似乎是变量范围的问题。 php.net/manual/en/language.variables.scope.php
-
请提供更多代码。如果周围有循环 - 显示它。
-
我已经用更多代码更新了这个问题。
-
我认为这与每次都重新初始化数组有关。