Foreach php function inside HTML select options

前端 未结 5 1915
粉色の甜心
粉色の甜心 2021-01-15 11:18

Im a newbie to this forum and have just started coding in php. Need some help. I have the following code



        
5条回答
  •  时光说笑
    2021-01-15 11:57

    And now let's go to ideal world :)

    Build data pairs database_id => name for options:

    $q = "SELECT pty.id, pty.pty_profile_name AS profile FROM pty, users 
          WHERE users.username = 'testaccount'";
    $r = mysqli_query($dbc, $q);
    
    $values = array();
    while($r = mysqli_fetch_row($r)) {
        $values[$r[0]] = $r[1];
    }
    

    Never use @ when working with database, why do you want to suppress errors instead of preventing/handling them?

    Now you have real database IDs and respective values (in general, using unique IDs are better... if nothing else they have greater entropy - more efficient search). And sice displaying select box is really common in webs, lets:

    function selectbox( $values = array(), $attributes = array(), $selected_value = null)
    {
        // Header
        echo ' $val){
            echo ' ' . htmlspecialchars($key) . '="' . htmlspecialchars( $val) . '"';
        }
        echo '>';
    
        // Values
        foreach( $values as $key => $val){
            echo '';
        }
        echo '';
    }
    

    And now usage :)

    'pty_select')); ?>

    And what to do with it then?

    $id = (int)(isset( $_POST['pty_select']) ? $_POST['pty_select'] : 0);
    $name = null;
    if( $id && isset( $values[$id])){
        $name = $values[$id];
    }
    

提交回复
热议问题