简体   繁体   English

使用PHP PDO并在Select中使用%动态查询Mysql

[英]Dynamically Query Mysql using PHP PDO and using % in Select

I have queried the database and got a list of database names that match my criteria. 我查询了数据库,并得到了符合我的条件的数据库名称列表。 This is what I ran to get the information. 这是我为了获取信息而运行的。

$sql = "SELECT DISTINCT tb.TABLE_SCHEMA
                FROM 
                    INFORMATION_SCHEMA.TABLES AS tb
                        INNER JOIN
                    INFORMATION_SCHEMA.TABLES AS tb2
                WHERE tb.TABLE_NAME like '%OPTION%'
                AND tb2.TABLE_NAME like '%USER%'"; 
    $query = $handler->prepare($sql); 
    $query->execute(); 
    $dbnames = $query->fetchAll(PDO::FETCH_COLUMN);

What I am trying to accomplish: Now that I have the names, I need to run through each database so that I can get the list of websites, email of admin and user login. 我要完成的工作:现在已经有了名称,我需要遍历每个数据库,以便获取网站列表,管理员电子邮件和用户登录名。 I know I can achieve this individually, but I am trying to do this dynamically with variables. 我知道我可以单独实现,但是我正在尝试使用变量来动态实现。 The select statement below would run and give me my answer. 下面的select语句将运行并给出我的答案。 However the prefix before the underscore in the FROM ysY6q8hmL7_options is different in each database. 但是,在每个数据库中,FROM ysY6q8hmL7_options下划线之前的前缀都不同。

SELECT option_value  FROM `ysY6q8hmL7_options` WHERE `option_name` = 'home' 

I tried this code but consistently get an error. 我尝试了此代码,但始终出现错误。 How can I solve this problem. 我怎么解决这个问题。 How can I run the queries dynamically without knowing the full name of each table. 如何在不知道每个表全名的情况下动态运行查询。 thank you. 谢谢。

foreach ($result as $val) {   
    $sql = "SELECT option_value FROM $val.%_options WHERE option_name = 'home'"; 
    $query = $handler->prepare($sql); 
    $query->execute(); 
    $dbnames = $query->fetchAll(PDO::FETCH_ASSOC);
    printResultConsole($dbnames); 

Your logic looks ok, but why do you have that percent sign in the table name ? 您的逻辑看起来还不错,但是为什么在表名中使用百分号呢? That's probably what is causing an error (whose message you should have shared, by the way). 这可能是导致错误的原因(顺便说一句,您应该共享其消息)。

Try this instead : 试试这个代替:

    $sql = "SELECT option_value FROM " . $val . "_options WHERE option_name = 'home'"; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM