在 PHP 字符串中格式化 MySQL 代码

2022-08-30 17:32:35

是否有任何程序IDE可以在PHP字符串中格式化MySQL代码,例如我使用PHPStorm IDE,但它无法做到这一点。

它为PHP和MYSQL执行此操作,但不为php字符串中的MYSQL执行此操作。我准备使用新的IDE,因为现在我必须手动格式化数百个数据库请求,这些请求是一行并且不可读。我选择的唯一标准是ide可以自动做到这一点。

<?php
...
$request1 = "select * from tbl_admin where admin_id= {$_SESSION['admin_id']} and active= 1 order By admin_id Asc";
...
?>

应该成为

<?php
...
$request1 = "SELECT * 
               FROM tbl_admin 
                  WHERE admin_id = {$_SESSION['admin_id']}
                  AND active = 1
                      ORDER BY admin_id ASC";
...
?>

答案 1

在我看来,最好的方法是使用正则表达式或SED / AWK来格式化所有内容,它为我们提供了动态替换地图的奖励。但是,您可能遇到代码错误的可能性很高,因此这有点困难。

让我做一点工作,我可以看看我是否能想出一个好的解决方案。是否保证将所有 SQL 封装在双引号中?

编辑

试试这个

cd {{directory}} && find . -type f -print0 |
  xargs -0 perl -i.bak -pe 's/select/SELECT/g ; s/from/\n\tFROM/g ; s/where/\n\t\tWHERE/g ; s/and/\n\t\tAND/g ; s/order by/\n\t\tORDER BY/g ; s/asc/ASC/g ; s/desc/DESC/g ;'

下面是一个示例

$ printf '"select * from whatever where this = that and active = 1 order by something asc";\n' |
> perl -pe 's/select/SELECT/g ; s/from/\n\tFROM/g ; s/where/\n\t\tWHERE/g ; s/and/\n\t\tAND/g ; s/order by/\n\t\tORDER BY/g ; s/asc/ASC/g ; s/desc/DESC/g ;'

"SELECT * 
    FROM whatever 
        WHERE this = that 
        AND active = 1 
        ORDER BY something ASC";

漂亮吗?不,一点也不行,它有效吗....是的。

我会尝试创建一个过滤器文件,也许还有一个小的bash程序或其他东西,因为我有时间运行这个热混乱。

编辑

这里有一些修改后的代码,看起来更漂亮(sorta)

printf '$request1 = "select * from whatever where this = that and active = 1 order by something asc";\n' | 
perl -pe 's/select/SELECT/gi ; s/from/\n  FROM/gi ; s/where/\n    WHERE/gi ; s/and/\n    AND/gi ; s/order by/\n      ORDER BY/gi ; s/asc/ASC/gi ; s/desc/DESC/gi ;' | 
awk 'NR == 1 {pad = length($0)/2; print} NR > 1 {gsub(/\r/,""); printf "%*s%s\n", pad, " ", $0}'

__OUTPUTS__
$request1 = "SELECT * 
             FROM whatever 
               WHERE this = that 
               AND active = 1 
                 ORDER BY something ASC";

答案 2

据我所知,PhpStorm可以做到这一点,如果你使用heredoc语法

$request1 = <<<SQL
   SELECT * 
           FROM tbl_admin 
              WHERE admin_id = {$_SESSION['admin_id']}
              AND active = 1
                  ORDER BY admin_id ASC
SQL;

推荐