自动递增数组索引(PHP)

时间:2014-04-11 00:13:07

标签: php arrays indexing add

刚刚进行了搜索,找不到合适答案的问题。我正在尝试将product_id添加到数组的末尾,有些每次添加时都会添加,它也会添加到数组中。目前,每次添加product_id时,它都会替换之前的内容。我得到的只是Array [0]中的一个product_id .Below是我的代码中添加了数组的部分。然后我用

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'] . "'");
    }

1 个答案:

答案 0 :(得分:0)

当您执行$order时,您可以清除$order = array();中的先前值 只需删除该行,$order[] = $product_id;就会将另一个项目添加到数组中。