skip to Main Content
<?php
global $wpdb;
$result = $wpdb->get_results( "SELECT name FROM student_reg");
foreach ($result as $row){
    echo "<select name='name'>";
    echo "<option value='" . $row->name . "'>" . $row->name . "</option>";
    echo "</select>";
}
?>

This code fetch into many dropdown button not in one button. I want to fetch it into one dropdown button only. Anyone help me?

2

Answers


  1. Try like this:

    <?php
    global $wpdb;
    $result = $wpdb->get_results( "SELECT name FROM student_reg");
    echo "<select name='name'>";
    foreach ($result as $row) {
       echo "<option value='" . $row->name . "'>" . $row->name . "</option>";
    }
    echo "</select>";
    ?>
    
    Login or Signup to reply.
  2. You’re putting a full <select> inside each iteration of your foreach loop. You need to move those outside of the loop, and only retain the <option> inside it.

    global $wpdb;
    $result = $wpdb->get_results( "SELECT name FROM student_reg");
    
    echo '<select name="name">';
    foreach( $result as $row ){
        printf( '<option name="%s">%s</option>', esc_attr($row->name), $row->name );
    }
    echo '</select>';
    

    WordPress also has some escaping functions like esc_attr() that you should be using when you’re outputting values into HTML attributes, URLs, etc.

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