简体   繁体   中英

Inserting Data Mysql with One Value from another table

I have a question, how to insert data into database table (mysql) which all data retrieve from php post form and 1 from another table like this?

PHP Get:

$nama           = $_POST['nama'];
$alamat         = $_POST['alamat'];
$jenis_kelamin  = $_POST['jenis_kelamin'];
$shift          = $_POST['shift'];

Insert Query:

    INSERT INTO test (`id`, `nama`, `alamat`, `jenis_kelamin`, `shift`) VALUES 
('$nama','$alamat','$jenis_kelamin', select id from shift where shift_name = '$shift')"

Here is the output when I try to run these code:

Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'select id from shift where shift_name = 'pagi')' at line 1

Try using insert into select from

INSERT INTO test ( `nama`, `alamat`, `jenis_kelamin`, `shift`) 
   select '$nama','$alamat','$jenis_kelamin','$shift' from shift where shift_name = '$shift'

insert语句的values部分中的子查询应使用括号括起来。

Insert into table_name values(col1, col2) values (val1, (select val2 from...));

Note: You have to enclose the parenthesis to the select statement that you are using.

Basically when you are concatenating the PHP values to the mysql statements you have to use '' for inserting the string values into the DB.

<?php
$nama           = $_POST['nama'];
$alamat         = $_POST['alamat'];
$jenis_kelamin  = $_POST['jenis_kelamin'];
$shift          = $_POST['shift'];

$query = "INSERT INTO test (`id`, `nama`, `alamat`, `jenis_kelamin`, `shift`) VALUES ('".$nama."','".$alamat."','".$jenis_kelamin."', (SELECT id from shift where shift_name = '".$shift."'))";
?>

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