duanhuanzhi6431 2013-04-25 15:13
浏览 7

PHP / SQL将用户标识添加到新用户的查找表中

I have a script which adds a new user to the database and stores them in the users table. I also have a contracts table (a list of contracts) and a look-up/linking table for users to contracts.

I want to know the best way to add a new user to the contracts table when you will not know what the unique ID they will be given is?

Example:

step 1 - Sign-up form has normal user inputs, username, password ect and a number of checkboxes for contracts (all contracts have a unique ID also).

step 2 - the form is submitted and users details are added to the user table and a unique ID is generated for that new user.

step 3 - the contracts selected in step 1 are inserted into the users_contracts table using the unique ID of the contracts selected and the unique ID of the new user.

This is where im having a brain block. How do I know what the new users unique ID will be?

The only way I can think at the moment is to INSERT the new user as normal, then do another query for the new username and pull the new users ID from the database then INSERT it in to the users_contracts table in a third query.

Something like:

INSERT INTO `users` _POST DATA FROM FORM

Then get the above INSERTED user and store in a variable:

SELECT FROM users _POST USERNAME

Then add it to the users_contracts table:

INSERT INTO users_contracts _POST contracts and the above created variable for the users ID

SORRY should mention im using PDO for the insert and all database activity.

  • 写回答

1条回答 默认 最新

  • douji8033 2013-04-25 15:17
    关注

    After running your user insert query, run:

    $userId = mysql_insert_id();
    

    Returns the ID of the previously inserted row.

    EDIT: Since someone will mention it, you should actually use mysqli_insert_id() because mysql_insert_id() and other MySQL (as opposed to MySQLi) will be deprecated eventually.

    评论

报告相同问题?

悬赏问题

  • ¥15 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析