-1

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.

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

6
  • What does var_dump($results); show? Commented Sep 29, 2023 at 21:07
  • @Barmar I get this: var_dump: array(0) { } Commented Sep 29, 2023 at 21:13
  • 1
    That means there were no options with that option name. Commented Sep 29, 2023 at 21:15
  • Instead, you can use directly get_option() like: <?php echo get_option('apv_price'); ?> Commented Sep 29, 2023 at 21:16
  • I added a screenshot of the info in the database. In this particular instance, this price is not related to the $product. Commented Sep 29, 2023 at 21:18

1 Answer 1

1

$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'))); ?>);
Sign up to request clarification or add additional context in comments.

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.