如何将名称转换为 id


How can i convert a name to id

我正在尝试将具有外键的 id 更新为另一个名称表。我有一个下拉菜单,在下拉菜单中,我有表 NAME_TEST 中的名字。我需要选择名称,但我想要的插入是:

INSERT INTO (test) values (the value that i need is the ID of selected name)       

法典:

<html> <h1>Update form</h1></html>
                     <?php
                     if (isset($_POST['submit'])) {
                     $connect = mysqli_connect('localhost', 'root', '', 'test');
                     $query = "UPDATE test SET                                               location_name='".$_POST['new_location']."' WHERE id='".$_POST['location']."' LIMIT 1";
    $res = mysqli_query($connect, $query);
    if (!$res) {
        die("Something went wrong");
    }
}
            // This is the code to load the select options
            $connect = mysqli_connect('localhost', 'root', '', 'test');
            $query = 'SELECT * FROM name_test';
            $res = mysqli_query($connect, $query);
            echo "Choose setup";
            $options = array();

            while($row = mysqli_fetch_assoc($res)) {
                $options[] = $row;
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>"><BR><BR>
    <select name="location">
        <option value="0">--- Select an option ---</option>
        <?php foreach ($options as $option): ?>
            <option value="<?= $option['id'] ?>"><?= $option['name'] ?></option>
        <?php endforeach; ?>
    </select><br /><BR><BR>
    <B> New name:</B> <BR>  <input type="text" name="new_location"><br /><BR><BR>
    <input type="submit" name="submit" value="Update" />
</form>

您可以使用join。 这个想法是这样的:

INSERT INTO t(nameid)
    select nameid
    from names n
    where n.name = ?;

t是要插入到的表。 names是具有名称 ID 和名称的表。