php - 添加 WHERE、SELECT、ORDER BY 等...就像通过 PHP 的链式 SQL

标签 php mysql parsing

我需要添加 WHERE、SELECT、ORDER BY 等...就像通过 PHP 的链式 SQL 一样。我用https://github.com/greenlion/PHP-SQL-Parser将 SQL 溢出到数组中,然后形成 SQL

我需要一个中间代码。我可以添加 SELECT、WHERE、ORDER BY 等...并且我可以测试表、字段、PHPSQLParser 数组中是否存在。

示例:

$sSql = 'Select a, b, c from table1 inner join table2 on (table1.a = table2.a) where b = 900';

# Return array SQL
$aParser = new PHPSQLParser( $sSql );
$aParser = $aParser->parsed;

// I need to intermediate code add fields, conditions, etc. //

// Create the SQL through the array
$creator = new PHPSQLCreator( $this->aParser );

// Show SQL
echo $creator->created;

最佳答案

您正在使用的包缺少处理已解析查询所需的方法。如果您编写自己的“查询生成器”包,则可以使用此包作为起点,这样您就不必编写解析 sql 的代码。或者更好的是,您可以完全使用不同的包,其中包含查询解析和构建。

这是一个:https://github.com/jasny/dbquery-mysql

它可以按照您要求的方式使用:

<?php
    use Jasny\DB\MySQL\Query;

    $query = new Query("SELECT * FROM foo LEFT JOIN bar ON foo.bar_id = bar.id WHERE active = 1 LIMIT 25");
    if (isset($_GET['page'])) $query->page(3);

    $filter = isset($_POST['filter']) ? $_POST['filter'] : array(); // array('type' => 'bike', 'price between ? and ?' => array(10, 20))
    foreach ($filter as $field => $value) {
        $query->where($field, $value);
    }

    $result = $mysqli->query($query); // SELECT * FROM foo LEFT JOIN bar ON foo.bar_id = bar.id WHERE (active = 1) AND (`type` = "bike") AND (`price` between 10 and 20) LIMIT 25 OFFSET 50

关于php - 添加 WHERE、SELECT、ORDER BY 等...就像通过 PHP 的链式 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33441486/

相关文章:

php - Mysql Alias 中的自定义数组索引

php - 使用检测移动浏览器脚本进行平板电脑检测?

php - 将文件包含到命名空间中

c# - 根据mysql中记录的数字在组中检查单选按钮

sql - SELECT 获取数据还是将其存储在字段中?

c++ - 使用 Bison/Antlr/Packrat/Elkhound/编写的 LLVM JIT 解析器

php - 保护柜台 View 以免被操纵

php - 帮我为 iou Web 应用程序设计数据库架构

Javascript - 解析 XML 文档以创建数组

javascript - 使用 Javascript 从关键字搜索返回 Youtube 视频 URL