Using Chained Properties Inside $wpdb->prepare()

If you’re using $wpdb->prepare() to query a custom table, you can’t pass the table name in as an argument because it will be single-quoted, which would be a MySQL syntax error. Instead, you need to insert the variable directly into the double-quoted query string and let PHP parse it out.

That creates a new problem, though, if the table name is stored in a chained property. PHP will only parse out the first level, so it’ll come out as something like “database_name.Object ID #3->column_name”. To fix that, you need to wrap the entire chain in curly braces, this like:

$resultRows = $wpdb->get_results(
    "SELECT result_id FROM `{$this->cfs->resultsTable}` WHERE user_id = %d",
  ), ARRAY_A

Leave a Reply

Your email address will not be published. Required fields are marked *