I'm trying to write a SQL query to hit my WordPress database as I need some of the info for my front end. However, I'm not getting anything from it. I can see the info in the database itself, so something is wrong with my query string.
$priceQuery = "SELECT `option_value` FROM {$wpdb->prefix}`options` WHERE `option_name` = 'apv_price'";
$results = $wpdb->get_results($priceQuery, 'ARRAY_A');
I'm using the following <script>
to log out my info to the browser:
<script>
console.log("results: ", <?php echo implode(",", $results) ?>);
</script>
However, all I get is result:
in my console. I used the CodeWP AI to help me write this, and it suggested the {$wpdb->prefix}
for the query. The table is fully titled wp_options
. I've tried the query with both and still get no result. Does anybody see where I went wrong?
Thanks.
$results
is a 2-dimensional array -- each element of the array is a row of the results represented as an associative array.
So use array_column($results, 'option_value')
to get the array of values, and implode this.
You also need to quote the resulting string when substituting it into JavaScript. Use json_encode()
to convert it to a properly formated JavaScript string.
console.log("results: ", <?php echo json_encode(implode(",", array_column($results, 'option_value'))); ?>);