简体   繁体   English

获取last_inserted_id-PHP-Wordpress

[英]Get last_inserted_id - PHP - Wordpress

Is there a way to insert data in two tables at the same time and then at the same moment to get the id from first table and insert it to the second table in my field named user_id let's say. 有没有一种方法可以同时在两个表中插入数据,然后同时从第一张表中获取ID,然后将其插入到名为user_id的我的字段中的第二张表中。 I tried something with this but it's not working. 我尝试了一些方法,但是没有用。 Am I missing something? 我想念什么吗? I want to do this because I need to have same ids of the same records in the two tables to make an update. 我想要这样做是因为我需要在两个表中具有相同记录的相同ID才能进行更新。 Thanks. 谢谢。

global $current_user;
get_currentuserinfo();
$user_id = $current_user->ID;
$table = 'tst_test';
$data = array( 
          'user_id' => $user_id, 
          'username' => $_POST['fname'], 
          'email' => $_POST['email'], 
          'telefon' => $_POST['phone_number']
); 
$format = array('%s','%s', '%s', '%s'); 
$send_data = $wpdb->insert($table, $data, $format);

You can call the $wpdb->insert_id after $wpdb->insert(_) , this will return the last inserted id of the the object, then you can use the same for the second record. 您可以在$wpdb->insert(_)之后调用$wpdb->insert_id ,这将返回对象的最后插入的ID,然后可以将其用于第二条记录。

For more information on the DB operations of Wordpress 有关Wordpress的数据库操作的更多信息

No such mechanism is supported by MySQL, but you can achieve it by MySQL不支持这种机制,但是您可以通过以下方式实现

  1. Insert the data in first table, the user_id column of this table must be auto increment 在第一个表中插入数据,该表的user_id列必须是自动递增的

     INSERT INTO table1 (user_id, username, email, telefon) VALUES (NULL, $_POST['fname'], $_POST['email'], $_POST['phone_number']) 
  2. Get auto increment id of last step's insert statment 获取上一步的插入语句的自动增量ID

     $userID = mysql_query("SELECT LAST_INSERT_ID()"); 
  3. Use the userID from last step to insert in second table 使用上一步中的userID插入第二个表

     INSERT INTO table2 (user_id, username, email, telefon) VALUES ($userID, $_POST['fname'], $_POST['email'], $_POST['phone_number']) 

You can try using the stored procedure try this code. 您可以尝试使用存储过程尝试此代码。

CREATE TABLE a
( user_id   INT UNSIGNED PRIMARY KEY AUTO_INCREMENT
, a_text CHAR(12));

CREATE TABLE b
( b_id   INT UNSIGNED PRIMARY KEY AUTO_INCREMENT
, user_id   INT UNSIGNED 
, b_text CHAR(12));

DELIMITER $$

CREATE PROCEDURE double_insert
( input_a CHAR(12), input_b CHAR(12))
BEGIN
  START TRANSACTION;
  INSERT INTO a VALUES (NULL, input_a);  
  INSERT INTO b VALUES (NULL, last_insert_id(), input_b);
  COMMIT;
END;

if you are using PDO the call like this hope this will help you. 如果您使用的是PDO,则这样的电话希望对您有所帮助。

$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000); 

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

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