timbmg
timbmg

Reputation: 3328

Foreign Key in web forms

I am creating web forms for users to enter data into my database. Now I am thinking of a good way to enter/choose foreign keys. For example I have a table A which has 1:n relation to table B. I want to create a form for table b. The user can enter the normal information in input boxes. To enter the foreign key I thought about a dropdown list, where all entries of table A are displayed. Unfortuanately, the dropdown list of HTML can only display one coulmn. So I cannot display the ID and the name of the picked entry.

Does someone know a smart way to display the name of the entry but pass the id?

Now I am doing something like this. But here only the id of the picked entry is displayed for the user. I want to display the name, but pass the id.

<select name="input_modul">
<?php 

$sql = "SELECT id, Name FROM tableA;";

if($result = $con->query($sql)) {
    $rows = $result->num_rows;
    while($row = $result->fetch_array()) {                                    
        echo "<option>". $row['id'] . "</option>";
    }                   
}
?> </select>   

Upvotes: 0

Views: 139

Answers (1)

Allmighty
Allmighty

Reputation: 1519

Quite simply pass $row['id'] to the value-attriubute of the option-element

echo "<option value=\"" . $row['id'] . "\">" . $row['name'] . "</option>";

This way, the value of $row['name'] will be the displayed value in the list, while $row['id'] will be passed along to do stuff with (get / post / others)

Upvotes: 1

Related Questions