简体   繁体   中英

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. However the prefix before the underscore in the FROM ysY6q8hmL7_options is different in each database.

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'"; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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