Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass column from db query result to javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edited to add image of info in DB:
enter image description here

>Solution :

$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'))); ?>);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading