尝试在数组中的数据库中插入添加到购物车中的数据


Trying to insert data which is added to my cart in my database which is in array

case "add":
  if (!empty($_POST["quantity"])) {
    $productByCode = $db_handle - > runQuery("SELECT * FROM tblproduct WHERE code='".$_GET["code"]."'");
    $itemArray = array($productByCode[0]["code"] => array('name' => $productByCode[0]["name"], 'code' => $productByCode[0]["code"], 'quantity' => $_POST["quantity"], 'price' => $productByCode[0]["price"]));
    if (!empty($_SESSION["cart_item"])) {
      if (in_array($productByCode[0]["code"], $_SESSION["cart_item"])) {
        foreach($_SESSION["cart_item"] as $k => $v) {
          $name = mysql_real_escape_string($v['name']);
          $code = mysql_real_escape_string($v['code']);
          $qunatity = mysql_real_escape_string($v['quantity']);
          $price = mysql_real_escape_string($v['price']);
          $con = mysqli_connect("retail", "RS", "....", "rs");
          $query = "insert into addtocart(name,code,quantity,price)  values('$name','$code','$quantity','$price')";
          mysql_query($sql) or exit(mysql_error());
          if ($productByCode[0]["code"] == $k)
            $_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
        }
      } else {
        $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"], $itemArray);
      }
    } else {
      $_SESSION["cart_item"] = $itemArray;
    }
  }
  break;

你不能直接将数组插入到mysql,因为mysql不理解php数据类型。Mysql 只理解 SQL。因此,要将数组插入 mysql 数据库,您必须将其转换为 sql 语句。这可以手动完成,也可以由库完成。输出应为 INSERT 语句。

这是一个标准的 mysql 插入语句。

INSERT INTO TABLE1(COLUMN1, COLUMN2, ....) VALUES (VALUE1, VALUE2..)

如果你有一个带有名称addtocart的表,其中包含数组键中显示的列,您可以使用这个小片段插入。下面介绍了如何将数组转换为此语句。

$columns = implode(", ",array_keys($insData));
$escaped_values = array_map('mysql_real_escape_string', array_values($insData));
$values  = implode(", ", $escaped_values);
$sql = "INSERT INTO `addtocart`($columns) VALUES ($values)";

我希望它能为你工作。请让我知道发生任何错误。

如果你想将数组保存到MySQL,你必须serialize((数组然后插入到MySQL

当你从MySQL返回它时,它再次使用unserialize((数组来处理它

http://php.net/manual/en/function.serialize.php