Display Results from query in a select tag in wordpress page?

I have a WordPress page that connects to an external database from WordPress using the following code:

$my_wpdb = new wpdb('me', 'password', 'database', 'localhost');

$myrows = $my_wpdb->get_results( "SELECT Name FROM testing" );

...then i use print_r($myrows); and get the following:

Array
(
  [0] => stdClass Object (
            [Name] => Jesus
         )

  [1] => stdClass Object (
            [Name] => James
         )

  [2] => stdClass Object (
            [Name] => Matt
         )
)

Now I need to output the names inside those objects in a select tag using php.

Any help would be appreciated.

Answers


There you go:

<select>
<?php foreach ($myrows as $myrow) : ?>
    <option value=""><?php echo $myrow->Name; ?></option>
<?php endforeach; ?>
</select>

Also, by the looks of your table it might be easier to just use WordPress get_col() function, which works pretty much the same way as get_results but should directly return "Name".


EDIT - Maybe the [insertphp] plugin likes this version better:

<select>
[insertphp]
foreach ($myrows as $myrow) {
    echo '<option>' . $myrow->Name . '</option>';
}
[/insertphp]
</select>

Also, please provide any error info that might help troubleshoot the problem otherwise.


Need Your Help

SQL Server database on Azure UNIQUE KEY constraint crash

.net sql-server entity-framework azure

After launching promo campaign of our software yesterday we've met some strange problems with our SQL Server database. This error occurs when users did signup for an account at our website. When it...

Installing Google Maps/Places API Cocoa pod on iOS. How?

ios google-maps cocoa install

I'm trying to install the Google Maps API onto my Macbook Pro. I have followed the instructions on the website here but got as far as Step 3. How do I