1

Here's my code:

global $wpdb;
$table_name = $wpdb->prefix . 'product_codes';

// Check if codes exist
$query = $wpdb->prepare( "SELECT * FROM %s", $table_name ); 
$existing_data = $wpdb->get_results( $query );

// Returns empty array despite data existing
print '<pre>';
print_r( $existing_data );
print '</pre>';

If I enter the table name literally, it works. If I print out the table name variable, it shows the correct string. But for some reason when I use the code above, I get an empty array - zero results.

5

The issue is that in My/SQL table names are not strings. So 'wp_product_codes' is being interpreted as a string instead of as an actual table. This is why you usually don't see tables passed into wpdb::prepare() - you should know the table names as they won't change where wpdb::prepare() is meant for data that you may not know / can't be trusted and needs to be sanitized. So let's modify the query:

$existing_data = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}product_codes" );
printf( '<pre>%1$s</pre>', print_r( $existing_data, 1 ) );
die();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.