繁体   English   中英

将多维数组插入MySQL Table文本字段

[英]Inserting a multidimensional array into a MySQL Table text field

我想在MySQL数据库字段中插入一个多维数组,以便以后可以轻松地从数据库中读取它,再返回到数组中。 实现此目标的最佳方法是什么?

我尝试了以下无济于事:

$id    = "MXB-487"
$items = Array(Array("Coffee", "Blend", "500"), Array("Coffee1", "Blend1", "250"));
$items = implode(",", $items);
mysqli_query($con,"INSERT INTO carts (id, items) 
VALUES ($id, $items)");

/*Code that pulls the array from the Database based on id and stores in variable $info*/
restored_mdarray = explode(",", $info);

MySql中的ID通常是唯一的(我很确定您以这种方式指定了ID)。 因此,您不能共享多个项目的ID。 此外,内爆最终将导致以下查询:

INSERT INTO carts (id, items) VALUES(MXB-487, Array, Array)

由于您要尝试内向分解多维数组,因此不会递归内向分解。

您应该做的是遍历对象,我不确定这里的关系如何工作,但是看起来您需要一个关系表来连接这些项目。 考虑以下结构:

    Carts:
    +----------+-----------+
    |    ID    |   Name    |
    +----------+-----------+
--<-|  MXB-487 | Blah blah |
|   +----------+-----------+
|
|   Items:
|   +----------+-----------+----------+-----------+
|   | Cart_ID  | Type1     | Type 2   | Amount    |
|   +----------+-----------+----------+-----------+
--->| MXB-487  | Coffee    | Blend    | 500       |
    +----------+-----------+----------+-----------+

为了在PHP中实现该功能,您需要执行以下操作:

<?php
$id = "MXB-487";
$items = array(
    array("Coffee", "Blend", "500"),
    array("Coffee1", "Blend1", "500"),
);

$sql = "INSERT INTO actions (cart_id, type1, type2, amount) VALUES ";

$items_sql = array();
if (count($items)) {
    foreach ($items as $item) {
        $items_sql[] = "('$id', '{$item[0]}', '{$item[1]}', '{$item[2]}')";
    }
}

$sql .= implode(", ", $items_sql);

然后运行查询。

它看起来像这样:

INSERT INTO actions (cart_id, type1, type2, amount) VALUES ('MXB-487', 'Coffee', 'Blend', '500'), ('MXB-487', 'Coffee1', 'Blend1', '500')

您可以稍后选择:

<?php
$id = "MXB-487";

$sql = "SELECT * FROM actions WHERE (cart_id = '$id')";

尽管作为旁注,但我建议您研究PDO以及如何绑定值,或者至少学习在SQL中转义您的值以防止将来注入。

我推测了表的结构,当然您可以根据需要进行修改。

要通过SQL正确连接表(以稍后固定访问),可以在定义表时使用FOREIGN KEY:

CREATE TABLE actions (
    id INT(11) NOT NULL AUTO_INCREMENT,
    cart_id VARCHAR(32) NOT NULL,
    type1 VARCHAR(32) NOT NULL,
    type2 VARCHAR(32) NOT NULL,
    amount INT NOT NULL,

    PRIMARY KEY (id),
    FOREIGN KEY (cart_id) REFERENCES carts(id)
)

使用serialize

$a = array(array(1,2,3), array(3,4,5));
$b = serialize($a);
# write $b to and later read $b from database
$c = unserialize($b);
$a == $c   # => true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM