简体   繁体   中英

Using database output in HTML Select Tag with PHP

I have the following working perfectly on a wordpress site.

<?php 

global $wpdb;

$results = $wpdb->get_results( "SELECT post_title FROM wp_posts WHERE post_type = 'show' AND post_status = 'publish' ORDER BY post_title ASC" );
$options = array();
foreach ($results as $result) {
$options[$result->post_title] =  $result->post_title;
}

echo '<select class="field" name="djshow">';
foreach ($options as $key => $value) {
echo "<option value='$key'" . ( $_GET['show'] == $value ? " selected='selected'" : "" ) . ">$value</option>";
}
'</select>';

?>

It searches the database for every instance of post_title from wp_posts where the post_type is show and the post_status is public . It then sorts it and outputs it to the array before populating a Select tag with a list of every post_title that matches.

At the moment it outputs the post_title to both the option value and name fields....

What I would like to do is select another field ID in the original query to populate the option value while the post_title populates the name.

So the select would read something like this when rendered in html :

<option value="15">Post Title 1</option>
<option value="18">Post Title 2</option>
<option value="23">Post Title 3</option>
etc...

I think the correct query I need to use is this (but correct me if i'm wrong)

$results = $wpdb->get_results( "SELECT post_title,ID FROM wp_posts WHERE post_type = 'show' AND post_status = 'publish' ORDER BY post_title ASC" );

But that's where my limited knowledge let's me down...

How would I assign the output of ID to the option value and post_title to the name of the select tag?

When you query for several values you can use a comma to separate them. In your code

post_title AND ID

should be

post_title, ID

Your return value are in $results, your foreach could be

foreach ($results as $result) {
echo "<option value='$result->ID'" . ( $_GET['show'] == $result->ID ? " selected='selected'" : "" ) . ">$result->post_title</option>";
}

not sure if your $_GET holds the post_title or the ID

After changing the SQL to include both post_title and ID you really only need to fix this part:

foreach ($results as $result) {
  $options[$result->post_title] =  $result->post_title;
}

Which should now be:

foreach ($results as $result) {
  $options[$result->ID] =  $result->post_title;
}

Because in the next foreach what you have in $key is coming from what you put in the brackets there, and $value from the right side of the assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM