1

This should be fairly simple. I've crafted an SQL query that dumps all matching database table names to an array. I want to print them out, yet for some reason I cannot. Please help!

Database tables are named: example_1, example_2, etc.

My code:

$sql = "SHOW TABLES LIKE 'example_%'"; $results = $wpdb->get_results($sql); 

Doing a print_r($results) shows that all the table names were successfully retrieved. Example output:

Array ( [0] => stdClass Object ( [Tables_in_wordpress (example_%)] => example_1 ) [1] => stdClass Object ( [Tables_in_wordpress (example_%)] => example_2 ) ) 

So then I tried:

foreach($results as $res) { echo $res; } 

But no luck. How can I iterate through $results to print out each table name? Is there something like $results[0].value I could use to retrieve the values?

3 Answers 3

9

I believe this is what you need to do:

$sql = "SHOW TABLES LIKE '%'"; $results = $wpdb->get_results($sql); foreach($results as $index => $value) { foreach($value as $tableName) { echo $tableName . '<br />'; } } 

The => will separate the key and value from a multidimensional array.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup, that did it! You're the man. Thanks a bunch... just learned something new.
2

Try following code.

global $wpdb; $res = $wpdb->tables(); var_dump($res); 

2 Comments

This is the right way to get the list of tables in WordPress.
This is giving only the WordPress default tables not the custom tables added by plugin or theme @Mybbor is the right way to get all table name from DB
0

This can be simplified using array_column.

$tables = array_column( $wpdb->get_results("show tables"), "Tables_in_local" ); foreach( $tables as $table ) { echo $table; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.