解析SQL查询的SELECT子句到一个PHP数组 [英] Parse SELECT clause of SQL queries into a PHP array

查看:216
本文介绍了解析SQL查询的SELECT子句到一个PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是多为之前的发送到服务器分析在PHP中的查询。非常复杂的IM为什么这样做,所以我宁愿不进入这样做的原因。

This is more for analyzing a query in PHP BEFORE it's sent to the server. Very complicated why im doing this, so i'd rather not go into the reason for this.

在PHP中,我需要的字段选择保存到一个PHP数组。因此,采取此查询,例如:

In PHP, i need to store the field selections into a php array. So take this query for example:

SELECT user_id,username,DATE(join_datetime) as join_date, (SELECT COUNT(1) FROM foobar WHERE foonum IN (5,4,6) and user_id = users.user_id) as myfoo_count 
FROM users 
WHERE user_id = 123

因此​​,在这种情况下,我需要存储user_ID的,用户名,DATE(join_datetime)为join_date,(SELECT COUNT(1)从foobar的WHERE foonum IN(5,4,6)和USER_ID = users.user_id)作为myfoo_count到数组爆炸由一个逗号(,)。所以,我会得到:

So, in this case I need to store "user_id,username,DATE(join_datetime) as join_date, (SELECT COUNT(1) FROM foobar WHERE foonum IN (5,4,6) and user_id = users.user_id) as myfoo_count" into an array exploded by a comma (,). So I would get:

array (
  [1] => 'user_id',
  [2] => 'username',
  [3] => 'DATE(join_datetime) as join_date',
  [4] => '(SELECT COUNT(1) FROM foobar WHERE foonum IN (5,4,6) and user_id = users.user_id) as myfoo_count'
)

我已经尽可能提取查询的领域得到了一部分,但被困在试图通过逗号爆炸等领域的IM。的主要问题与子查询是可能在他们逗号太(参见实施例)。

I have gotten as far as extracting the fields part of the query, but im stuck on trying to explode the fields by comma. The main problem being with subqueries which might have commas in them too (see example).

感谢您的帮助!

推荐答案

您会写一个解析器几乎一样复杂,因为MySQL的查询分析器(写在YACC /野牛为C)。它不会是一个普通的前pression还是有点字符串操作。这是一个非正规的语言,你不能没有一个实际的解析器解析。

You would have to write a parser almost as complex as MySQL's query parser (written in YACC/Bison for C). It's not going to be a regular expression or a little string manipulation. This is a nonregular language, you can't parse them without an actual parser.

您不能只是穿行字符串发现逗号和括号要么,SQL较复杂得多。你有恩pressions,函数调用,条件逻辑等,所有这些都可以用逗号任意深度嵌套和遍布括号中前pressions。

You can't just walk through the string finding commas and parentheses either, SQL is much more complex than that. You have expressions within expressions, function calls, conditional logic, etc. all of which can be nested arbitrarily deep with commas and parentheses all over.

http://dev.mysql.com/ DOC / refman / 5.0 / EN / EX pressions.html

如果你真的想用PHP来做到这一点,你有一个很大的工作提前自己。

If you really want to do this with PHP, you have a big job ahead of yourself.

这篇关于解析SQL查询的SELECT子句到一个PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆