【问题标题】:How to replace a string in entire mysql database php [duplicate]如何替换整个mysql数据库php中的字符串[重复]
【发布时间】:2019-06-13 08:38:37
【问题描述】:

我有一个 php 网站,其中以前存储在 /uploads/ 文件夹中的图像文件现在我创建了一个新文件夹 /files1/ 并且图像存储在新文件夹中,以前的图像也已移动到新文件夹中。但是数据库中以前的图像链接仍然包含旧路径 www.example.com/uploads/text.png ,有什么办法可以在整个数据库中使用 mysql 、 php 将“/uploads/”替换为“/files1/”

谢谢

【问题讨论】:

  • 更新您的数据库设计,以便您的路径仅存储在一个表中,为每条记录提供唯一的 id,并在其他表中引用该 id。这就是规范化数据库的优势(如今似乎没有人关心):如果这些路径需要批量更改,您只需要一个更新语句。

标签: php mysql mysqli


【解决方案1】:

如果您不反对在数据库上创建和运行stored procedure,那么您完全可以不使用 PHP。

create procedure `speditalltables`()
begin
    declare _strsql varchar(512);
    declare _table varchar(128);
    declare done int default false;
    declare res integer default 0;

    declare _cursor cursor for select `table_name` as 'name' 
            from `information_schema`.`tables` 
            where `table_type`='base table' and `table_schema`=database();

    declare continue handler for not found set done=true;



    open _cursor;

        repeat

        fetch _cursor into _table;

        if not done then


            /* different column names ~ edit as appropriate */
            set @strsql=concat("update `",database(),"`.`",_table,"` 
                set 
                `filepath`=replace( `filepath`, '/uploads/', '/files1/' ),
                `filepath2`=replace( `filepath`, '/uploads/', '/files1/' ),
                `filepath3`=replace( `filepath`, '/uploads/', '/files1/' ),
                `filepath4`=replace( `filepath`, '/uploads/', '/files1/' )");

            prepare stmt from @strsql;
            execute stmt;
            deallocate prepare stmt;


        end if;


        until done end repeat;

    close _cursor;

    select 'finished' as 'result';

    set done=null;
    set @res=null;
    set @_table=null;
end

【讨论】:

  • 所有表中的列名不同
  • 天哪……这会让你的生活变得棘手
  • 我需要对大约 200 个表的每个表运行查询,没关系
  • 您在这里谈论多少个不同的列名?如果没有太多,只需编辑存储过程中的 sql 查询以包含其他列
猜你喜欢
  • 2015-01-29
  • 1970-01-01
  • 2019-06-02
  • 2018-05-07
  • 2014-02-11
  • 2013-06-18
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多