dqhr76378 2019-01-15 19:41
浏览 62
已采纳

如何从另一个表的下拉列表中插入所选名称的ID?

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
  • 写回答

1条回答 默认 最新

  • drcrc28428 2019-01-15 19:50
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大