0

I have a table called person with column called language.

And also I have another table called language_table

CREATE TABLE language_table (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    designation VARCHAR(30) NOT NULL
)

It contains:

1 - english
2 - frensh
3 - arabic
4 - other

I wanted to put these 4 records into a <select options.

I have created this code, it works perfectly fine, but I don't know how to add another <select> with values from database.

How do I fetch the selected value from DB into <option>?

<?php
$query = mysqli_query($con, "SELECT * FROM person WHERE id=$id");
while ($result = mysqli_fetch_object($query, $con)) {
?>
<select name="sexe">
<?php
    if ($result->sexe == 'Masculin') {
        echo"<option value='Masculin' Selected>Masculin</option>";
        echo"<option value='Féminin' >Féminin</option>";
    } else {
        echo"<option value='Masculin' >Masculin</option>";
        echo"<option value='Féminin' Selected>Féminin</option>";
    } ?>
</select>
<?php
}
?>
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman May 28 '21 at 10:10

1 Answers1

0

I found a solution.

<?php
    $stmt = $con->prepare("SELECT * FROM person WHERE id=?");
    $stmt->bind_param("s", $id);
    $stmt->execute();
    $query = $stmt->get_result();
    while ( $result = mysqli_fetch_object($query)) 
    {
?>
<select>
<select name="language">
<?php
    $sql = mysqli_query($con, "SELECT designation FROM language_table");
    while($row = mysqli_fetch_object($sql))
    {
        if($row->designation == $result->language)
        {
            ?>
            <option value="<?php echo $row->designation;?>" SELECTED><?php echo $result->language;?></option>
            <?php
        }else{
            ?>
            <option value="<?php echo $row->designation;?>" ><?php echo $row->designation;?></option>
            <?
        }
    }
?>
  </select>
<?php
}
?>
Dharman
  • 30,962
  • 25
  • 85
  • 135