简体   繁体   中英

How to insert ID of a selected name from drop down list in another table?

I'm setting up a new simple website that it has two MySQL tables:

Client_table:

ID      Client_name
1      Alex
2      Bob
3      Clara

Order_table:

ID      Client_name
1     Bob
2     Clara
3     Bob

Using the following PHP code, the Client_name is taken by dropdown list from Client_table and add it to Order_table :

<?php
require('db.php'); \\$con = mysqli_connect('host', 'user', 'pass', 'db');
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
$client_name =$_REQUEST['client_name'];
$ins_query="insert into Order_table (`Client_name`) values ('$Client_name')";
mysqli_query($con,$ins_query) or die(mysql_error());
$status = "Added Successfully";
}
?>
<form name="form" method="post" action="">
    <select type="text" name="Client_Name" />
        <?php
        $result = $con->query("select * FROM Client_table");
        while ($row = $result->fetch_assoc())
            { echo "<option value='".$row['id']."'>".$row['Client_name']."</option>";}
        ?>
    </select>
    <p>
        <input class="btn" name="submit" type="submit" value="Add" />
    </p>
</form>

How to insert the ID of Client as Client_id in Order_table?

*NEW Order_table:

ID      Client_id      Client_name
1        2              Bob
2        3              Clara
3        2              Bob

You can select from Client_table when you're doing the INSERT to get the Client ID. You should also use a prepared statement to prevent SQL injection.

$ins_query= "INSERT INTO Order_table (Client_name, Client_id)
            SELECT Client_name, Client_id
            FROM Client_table
            WHERE Client_name = ?";
$ins_stmt = $con->prepare($ins_query) or die($con->error);
$ins_stmt->bind_param("s", $Client_name);
$ins_stmt->execute() or die($ins_stmt->error);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM