如何更新包含多个图像的行,该行最初在 php 中仅插入单个图像


How to update a row with multiple images which has only single image inserted initially in php

>我有一个表格,其中包含列 id、图像和组织名称。我最初为每个组织插入了单个图像,但我需要为每个组织使用多个图像更新它。我正在使用 php ver 5.4.16 和 mysql ver 5.6.12。

尝试使用分隔符,例如使用逗号并将其存储在表中:

id    image                                     organization
 1    path_to/img1.png                          org_name1
 2    path_to/img1.png,path_to/img2.png         org_name2

稍后,在提取记录后,使用爆炸函数将其提取到如下所示的数组中:

$images = explode(",", $data->image);

PS:请为图像字段提供足够的长度,例如,给它varchar(4000),这是为了确保不会有字符串截断

将表一分为二,并将表的 id 用作新映像表中的外键。("规范化"和"关系"应该是你的搜索标签) https://en.wikipedia.org/wiki/Database_normalization

或者,如果不能,则应使用 json 插入多个内容。 http://php.net/manual/en/book.json.php

您需要添加一个名为"image"的新表,其中包含列:

- id_img
- image
- ref_organisation_id (foreign_key)

在我看来,解决您的问题的最佳解决方案是稍微重新设计您的数据库架构 - 根据您在问题中给出的表的概述,现有表将无法为同一公司存储多个图像。

应该有一个表格用于组织

化,另一个表格用于与这些组织相关的图像。图像表将具有链接到组织表的键。

一个非常快速组合的示例数据库结构

+----+------------------+
| id | name             |
+----+------------------+
|  1 | ACME Web Company |
|  2 | ACME ISP         |
+----+------------------+

+----+--------+------------+
| id | org_id | image      |
+----+--------+------------+
|  1 |      1 | logo.jpg   |
|  2 |      1 | banner.jpg |
|  3 |      1 | badge.png  |
|  4 |      2 | logo.jpg   |
|  5 |      2 | banner.gif |
+----+--------+------------+
create table if not exists `organisations` (
  `id` int(10) unsigned not null auto_increment,
  `name` varchar(50) not null,
  primary key (`id`)
) engine=innodb auto_increment=3 default charset=utf8;
insert into `organisations` (`id`, `name`) values
    (1, 'acme web company'),
    (2, 'acme isp');
create table if not exists `org_images` (
  `id` int(10) unsigned not null auto_increment,
  `org_id` int(10) unsigned not null,
  `image` varchar(50) not null,
  primary key (`id`),
  key `org_id` (`org_id`),
  constraint `fk_org` foreign key (`org_id`) references `organisations` (`id`) on delete cascade on update cascade
) engine=innodb auto_increment=6 default charset=utf8;
insert into `org_images` (`id`, `org_id`, `image`) values
    (1, 1, 'logo.jpg'),
    (2, 1, 'banner.jpg'),
    (3, 1, 'badge.png'),
    (4, 2, 'logo.jpg'),
    (5, 2, 'banner.gif');