简体   繁体   English

如何通过id向另一个表插入数据

[英]How to insert data to another table by id

I want to complete user sign up.我想完成用户注册。 firstly user will write username and password, table called users, I have id as primary key.首先用户将写入用户名和密码,称为用户的表,我将 id 作为主键。 secondly user will write address, phone number and zipcode, table called userdata, I have userid as index(key).其次,用户将写入地址、电话号码和邮政编码,名为 userdata 的表,我将 userid 作为索引(键)。 I have did a relation between id from table user and userid from table userdata.我已经建立了表 user 中的 id 和表 userdata 中的 userid 之间的关系。

So now I want to insert data from php code I did two forms one for user and it has two input for username and password it works well and data inserted.所以现在我想从php代码插入数据我为用户做了两种形式,它有两个用户名和密码输入,它运行良好并插入数据。

in the second form I have select option has id from table users and it works well.在第二种形式中,我有选择选项具有来自表用户的 id,并且效果很好。 then in the same form I have three inputs phone number, address and zipcode.然后以相同的形式,我输入了三个电话号码、地址和邮政编码。 so the question is how I can insert the data to userdata by the same to the same id.所以问题是我如何将数据插入到用户数据中,相同的 id 。 so userid in table user will be the same id in table userdata.所以表 user 中的 userid 将与表 userdata 中的 id 相同。

I need sql code.我需要sql代码。
I used that : "INSERT INTO userdata(address, phone, zipcode) VALUE (:address, :phone, :zip) SELECT 'id' FROM 'users';"我用过:“INSERT INTO userdata(address, phone, zipcode) VALUE (:address, :phone, :zip) SELECT 'id' FROM 'users';”

First :第一的 :

$q = "NSERT INTO users(username, password) VALUE ('Adam', '12345678')";
$r = $connect->query($q);

//get the last id u inserted 
$last_id =  mysqli_insert_id($connect);

Second :第二 :

  $q = "NSERT INTO userdata(address, phone, zipcode,user_id) VALUE ('California', '12345678', '1111','$last_id')";
    $r = $connect->query($q);

and if you want to make the (id) not the (userid) the same just :如果您想让 (id) 不是 (userid) 相同,只需:

$q = "NSERT INTO userdata(id, address, phone, zipcode) VALUE ('$last_id','California', '12345678', '1111')";
        $r = $connect->query($q);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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