skip to Main Content

First post on stackoverflow. I have been following this site for a long time, and usually find what im looking for. But this has me perplexed.

Let me set the stage. I am developing a web driven program. I have WordPress, with the Divi theme from Elegant Themes. and I am using shortcodes to insert into the modules. I am a newbie (this says it all.)

Here is my problem. I have run a wpdb query that returns a single row of results.

$editresult = $wpdb->get_results ("SELECT `serialnumber`, `batttype`, `cells`, `fullvolts` FROM listbattery WHERE serialnumber = '$serialnumber'", ARRAY_A);

When I vardump this, i get the following.

array(1) {[0]=>array(4) {["serialnumber"]=>string(10)"battery #2" ["batttype"]=>string(5) "NiCad" ["cells"]=>string(1) "8"["fullvolts"]=>string(6)"12.125"}}

So with that being said, I know that the query is working fine. I know that I am receiving the information. What I can’t for the life of me figure out, is how to turn the results from each column into individual variables, so that I can insert each variable randomly throughout my page.

I have tried about 8 different methods so far. I hope you guys can help! thanks!!!

2

Answers


  1. You can loop through the result:

    foreach($editresult as $result) {
        $serialnumber = $result['serialnumber'];
        $batttype = $result['batttype'];
        $cells = $result['cells'];
        $fullvolts = $result['fullvolts'];
    }
    
    Login or Signup to reply.
  2. If only one row is expected to be returned, you can do the following

    $editresult = $wpdb->get_row("SELECT `serialnumber`, `batttype`, `cells`, `fullvolts` FROM listbattery WHERE serialnumber = '$serialnumber'", ARRAY_A);
    

    Then you can access returned values like

    $editresult['serialnumber']
    $editresult['batttype']
    $editresult['cells']
    $editresult['fullvolts']
    

    or if you change ARRAY_A to OBJECT, you will be able to access these values like so

    $editresult->serialnumber
    $editresult->batttype
    $editresult->cells
    $editresult->fullvolts   
    

    There is no need in get_results and foreach like shown in @nanodanger’s answer if you always expect to get only 1 row

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search