Redeem name instead of id in a select option from the PHP Mysql database

Asked

Viewed 233 times

0

Good night,

I’m populating a select option with data coming from the database, but when retrieving the value, I want to recover the name instead of the id.. has how to do this?

//chama o arquivo de configuração com o banco
 require_once("connection.php");

$q = 'SELECT id, user_name FROM users';

<select list="user" onkeyup="check_in_db()" class="message-input" name="user_name" id="user_name">
        <option>Selecione um usuario para enviar mensagem...</option>   

              <?php $r = mysqli_query($con, $q) ;
                if($r){
                  if(mysqli_num_rows($r) > 0){
                    while($row = mysqli_fetch_assoc($r)){ ?>
              <option  value="<?php echo $row['id'] ?>"><?php echo $row['user_name'] ?></option>
              <?php } 
            }
          }?>
      </select>

I want to reclaim the name of user_name option, instead of id... because I do a check and save this user_name in another database table, so I need to recover the name of this option, I know it’s a silly question, but I’m starting in PHP, I thank anyone who can help me...

  • Just replace $Row['id'] with $Row['Fieldname']... But best practice in relational databases recommends that you keep your username in a table and refer to that name by ID anywhere else you need it, either through a foreign key (FK) or by substitution (surrogate Key)

1 answer

1


If I understand correctly, do you want the same value displayed to the user in the combobox to be saved as well? Because the value displayed is user_name.

It’s quite simple actually, just do it:

 <option  value="<?php echo $row['user_name'] ?>"><?php echo $row['user_name'] ?></option>

Exchange the value within value id to user_name.

  • worked, perfect, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.