如何将名称转换为id

时间:2015-02-04 15:08:25

标签: php html mysql

我正在尝试将具有外键的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>

1 个答案:

答案 0 :(得分:0)

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

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

t是您要插入的表格。 names是名称为id和名称的表。