php mysql execute 2 insert statements based on first insert ID - php

This is what I am able to do:
When a user fills out a form to sign up the script will insert sign up info into table ps_reg_users. This table contains basic profile information.
I have added a Badge/Achievement section to display badges based on certain criteria.
What I need to do:
Once the user signs up, add that user to another table ps_badges with the id from the first query.
The id is set to auto increment on table ps_reg_users and inserts NULL upon submit, thus assigning the next id.
How would I INSERT a query to ps_reg_users then retrieve the id after it creates it to make another query based on that id?
PHP
$query = "INSERT INTO `" . DB_PREFIX . "reg_users` ( `id` , `first_name` , `last_name` , `password` , `email` , `date_time` , `user_status`, `verify_code` , `reward_points`, `ref_user`)
VALUES (NULL , '$first_name', '$last_name', '$password', '$e_email', '$date_time' , 'y', '$verify_code', '0' , '$ref_uid')";
This ^ works.
I need to execute this right after
$query = "INSERT INTO `" . DB_PREFIX . "badges` ( `user_id` , `pts_reputation` , `pts_comments` , `pts_uploads` , `pts_downloads` , `pts_featured` , `pts_activity`, `pts_refer`, `pts_donator` , `pts_country`)
VALUES (NULL , '0', '0', '0', '0', '0', '0', '0', '0', NULL)";
I hope im not over explaining, I think I need to tap into LAST_INSERT_ID() but how would I get it from the first query?

Basic sequence:
$sql = "INSERT ....";
$result = mysql_query($sql) or die(mysql_error());
$id = mysql_insert_id();
$sql = "INSERT .... (id,...) VALUES ($id, ...);"
$result = mysql_query($sql) or die(mysql_error());
Of course, you're still using an obsolete interface and SHOULD be switching to mysqli or PDO.

mysql_insert_id(); mysql function returns last inserted id

Related

What's wrong with my query that's making me not able to insert values from variables and a value from another table?

I'm looking to insert values from two sources (variables and a field from another table) into a new table. After some research, I found that this was possible, but cannot figure out how to accomplish this with my query.
Let me know if I have not provided enough context or code.
//Query to INSERT data
$query3 = "INSERT INTO `Checked_Out` (`name`, `quantityCheckedOut`, `checkedOut`, `returnDate`, `image`, `ID`) VALUES ('$name', '$quantityTaken', '$checkedOut', '$returnDate', '$ID')
SELECT `image` FROM `Checked_In` WHERE `ID` = '$ID'";
Try this:
$query3 = "INSERT INTO `Checked_Out` (`name`, `quantityCheckedOut`, `checkedOut`, `returnDate`, `image`, `ID`)
SELECT '$name', '$quantityTaken', '$checkedOut', '$returnDate', `image`, '$ID' FROM `Checked_In` WHERE `ID` = '$ID'";

[PHP][MySQL] How to insert data in 2 tables at same time?

I have a little problem to insert data in 2 tables and need some help with it.
For example:
Table 1:
CREATE TABLE tb1 (
tb1_id int(5) not null AUTO_INCREMENT PRIMARY KEY,
tb1_title varchar(50),
tb1_cat varchar(50)
);
Table 2:
CREATE TABLE tb2 (
tb2_id int(5) not null AUTO_INCREMENT PRIMARY KEY,
tb2_title varchar(50),
tb2_doc varchar(200),
id_tb1 int(5) not null REFERENCES tb1(tb1_id)
);
One entry of tb1 can have many information(rows) of tb2, but how to insert the id of tb1 in some rows of tb2?
formular.php:
$sqla = "INSERT INTO tb_1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat')";
$sqlb = "INSERT INTO tb_2 (tb2_title, tb2_doc, <b>[? ? ?]</b>) VALUES ('$tb2_title', '$tb2_doc', <b>[? ? ?]</b>)";
mysqli_query($db, $sqla);
mysqli_query($db, $sqlb);
What do I have to change here?
You can get the value of tb1_id using mysqli_insert_id(), and then insert that into tb2:
$sqla = "INSERT INTO tb1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat')";
if (mysqli_query($db, $sqla)) {
$tb1_id = mysqli_insert_id($db);
$sqlb = "INSERT INTO tb2 (tb2_title, tb2_doc, id_tb1) VALUES ('$tb2_title', '$tb2_doc', $tb1_id)";
mysqli_query($db, $sqlb);
}
Yes you can.. try this..
BEGIN;
INSERT INTO tb_1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat');
INSERT INTO tb_2 (tb2_title, tb2_doc, <b>[? ? ?]</b>,id_tb1) VALUES ('$tb2_title', '$tb2_doc', <b>[? ? ?]</b>,LAST_INSERT_ID());
COMMIT;
$sqla = "INSERT INTO tableA (col1, col2) VALUES (val1, val2)";
mysqli_query($db,$sqla);
$id = mysqli_insert_id($db); //add it here.
$sqlb = "INSERT INTO tableB (col1,col2) VALUES (val1, val2, ...)";
//then you can pass the id into your second query
//...

how to get the value of next autoincrements in php for mysql

ok so I have to run 2 updates that rely on each others IDs to sync properly.
conversation ID has to be in message table, where as MessageID has to be in the conversation table. and both are auto increment values.
mysql_query("UPDATE ow_base_user Set activityStamp = '$stamp' where id = '$profile_id' ");
mysql_query("INSERT INTO ow_base_user_online (id, userId, activityStamp, context) VALUES ('', '$profile_id', '$stamp', '1')");
$conid = mysql_query("SELECT ID AS id FROM ow_mailbox_conversation WHERE ID = IDENT_CURRENT") + 1;
$msgid = mysql_query("SELECT ID AS id FROM ow_mailbox_message WHERE ID = IDENT_CURRENT") + 1;
mysql_query("INSERT INTO ow_mailbox_conversation (id, initiatorId, interlocutorId, subject, read, deleted, viewed, notificationSent, createStamp, initiatorDeletedTimestamp, interlocutorDeletedTimestamp, lastMessageId, lastMessageTimestamp)
VALUES ('$conid', '$profile_id', '637', 'mailbox_chat_conversation', '1', '0', '1', '0', '$stamp', '0', '0', '$msgid', '$stamp')");
mysql_query("INSERT INTO ow_mailbox_message (id, conversationId, timeStamp, senderId, recipientId, text, recipientRead, isSystem, wasAuthorized)
VALUES ('$msgid', '$conid', '$stamp', '$profile_id', '637', 'hi there', '0', '0', '1')");
I thought possibly I could use IDENT_CURRENT + 1 to get the ID but when I echo it nothing comes up. sorry a bit new at this still can
--- edit ---
so tried using insert_id - problem then is the first number did not come back correctly. gave me a number almost 2x as large as it should be.
here is the code
mysql_query("INSERT INTO ow_mailbox_conversation (id, initiatorId, interlocutorId, subject, read, deleted, viewed, notificationSent, createStamp, initiatorDeletedTimestamp, interlocutorDeletedTimestamp, lastMessageId, lastMessageTimestamp)
VALUES ('', '$profile_id', '637', 'mailbox_chat_conversation', '1', '0', '1', '0', '$stamp', '0', '0', '', '$stamp')");
$conid = mysql_insert_id();
mysql_query("INSERT INTO ow_mailbox_message (id, conversationId, timeStamp, senderId, recipientId, text, recipientRead, isSystem, wasAuthorized)
VALUES ('', '$conid', '$stamp', '$profile_id', '637', 'hi there', '0', '0', '1')");
$msgid = mysql_insert_id();
mysql_query("UPDATE ow_mailbox_conversation Set lastMessageId = '$msgid' where id = '$conid' ");
--- edit ---
here is my full code everything seems to be working fine except Convarsation string is not inserting, then the $conid comes back really high in the debug.
$link = mysql_connect($OW_DB_HOST, $OW_DB_USER, $OW_DB_PASS);
if (!$link) {
die('Connection fail: ' . mysql_error());
}
mysql_select_db($OW_DB_NAME, $link);
// End of connection database
$stamp = time();
//1
mysql_query("UPDATE ow_base_user Set activityStamp = '$stamp' where id = '$profile_id' ");
mysql_query("INSERT INTO ow_base_user_online (id, userId, activityStamp, context) VALUES ('', '$profile_id', '$stamp', '1')");
$receiver_id = '637';
mysql_query("INSERT INTO ow_mailbox_conversation (id, initiatorId, interlocutorId, subject, read, deleted, viewed, notificationSent, createStamp, initiatorDeletedTimestamp, interlocutorDeletedTimestamp, lastMessageId, lastMessageTimestamp)
VALUES ('', '$profile_id', '$receiver_id', 'mailbox_chat_conversation', '1', '0', '1', '0', '$stamp', '0', '0', '', '$stamp')");
$conid = mysql_insert_id();
mysql_query("INSERT INTO ow_mailbox_message (id, conversationId, timeStamp, senderId, recipientId, text, recipientRead, isSystem, wasAuthorized)
VALUES ('', '$conid', '$stamp', '$profile_id', '$receiver_id', 'hi there', '0', '0', '1')");
$msgid = mysql_insert_id();
mysql_query("INSERT INTO ow_mailbox_last_message (id, conversationId, initiatorMessageId, interlocutorMessageId)
VALUES ('', '$conid', '$msgid', '0')");
$lastmsgid = mysql_insert_id();
mysql_query("UPDATE ow_mailbox_conversation Set lastMessageId = '$lastmsgid' where id = '$conid' ");
//End of script if devmode = false
// Output all used variables on devmode = true
if (DEVMODE){
echo 'Connection ok';echo '<br>';
echo '1 = ',$conid;echo '<br>';
echo '2 = ',$msgid;echo '<br>';
echo '3 = ',$lastmsgid;echo '<br>';
}
// End of testbench
mysql_close($link);
?>
you can use PDO::lastInsertId for getting id of last inserted row if you used PDO for connection. please refer:
http://php.net/manual/en/pdo.lastinsertid.php
alternatives,
http://php.net/manual/en/mysqli.insert-id.php
You cannot be sure of the next insert ID because your system will (I assume) be handling multiple feeds at a time as your site is not single-user
The best thing to do is to use three queries:
Insert into table 1 and retrieve the ID (id1)
Insert into table 2 (storing id1) and retrieve the new ID (id2)
Update table 1 (record ID id1) to store id2 in the relevant field
For this, I recommend using the InnoDB table and transactions. In the event of a failure, you can roll back to the state before anything started and minimise IDs being present which are unattached.
An alternative is to create a third table to store the relationship between the tables. Essentially, it stores id1 and id2 and nothing else
If possible, re-work your tables so that this mutual referencing is not required. It will make things easier in the long run
Finally, stop using the mysql_ functions. They are deprecated and removed completely in PHP 7. Use the PDO or mysqli_ functions. You'll thank me
the problem was errors with the structure
here is the fixed code.
mysql_query("INSERT INTO ow_mailbox_conversation (id, initiatorId, interlocutorId, subject, `read`, deleted, viewed, notificationSent, createStamp, initiatorDeletedTimestamp, interlocutorDeletedTimestamp, lastMessageId, lastMessageTimestamp)
VALUES ('', $profile_id, $receiver_id, 'mailbox_chat_conversation', 1, 0, 1, 0, $stamp, 0, 0, '', $stamp)");
$conid = mysql_insert_id();
notice the removed ' ' around the numbers and variables.

How to get the last inserted id on a table to use it on another insert on another table?

Im trying to get id of the last inserted id on a table called authors to use it in another insert to a table called mail.
As you can see this is inserting a new author in table authors, and right after the insertion it must insert a welcome message to the new author in table mail.
Im using mysql_insert_id() but its not working.
Nothing is saved to database and no errors occurs.
I know i should not use mysql_query but its ok, thats not the point here, just ignore this please.
if(!isset($row[email])){
$sql = "INSERT INTO authors VALUES (NULL, 0, '".$email."', '".$username."', NULL, '".$first."', '".$fullname."', '".$first."', NULL, NULL, NULL, NULL,'http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."', 0);";
mysql_query($sql);
$sqlmsg = "INSERT INTO mail VALUES (NULL, 1, mysql_insert_id(), 'Welcome', Hello! Welcome to the website!', 'unread', NOW, 0, 0)";
mysql_query($sqlmsg);
}
Why nothing happens when a new author is inserted?
Thank you.
You need to concatenate it within the string,
$sqlmsg = "INSERT INTO mail VALUES (NULL, 1, " . mysql_insert_id() . ", 'Welcome', Hello! Welcome to the website!', 'unread', NOW, 0, 0)";
Try saving it on a temporary variable before using it on the next query.
<?php
if(!isset($row[email])){
$sql = "INSERT INTO authors VALUES (NULL, 0, '".$email."', '".$username."', NULL, '".$first."', '".$fullname."', '".$first."', NULL, NULL, NULL, NULL,'http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."', 0);";
mysql_query($sql);
$author_id = mysql_insert_id();
$sqlmsg = "INSERT INTO mail VALUES (NULL, 1, $author_id, 'Welcome', Hello! Welcome to the website!', 'unread', NOW, 0, 0)";
mysql_query($sqlmsg);
}
?>
Use a select query on the table and order by 'id' desc with limit 1
select `id` from `authors` order by `id desc limit 1
will return the last id if it's auto incremented.

want to do a double MYSQL INSERT INTO to two different tables

I want to be able to insert into two different mysql tables using php with the second mysql insert being dependent on the member id of the first insert.
For example:
mysql_query("
INSERT INTO `member_users` (
`id`,
`first_name`,
`last_name`,
`username`,
`password`,
`address1`,
`address2`,
`postcode`,
`access`,
`expires`
) VALUES (
NULL,
'$fname',
'$lname',
'$email',
'$passhash',
'$add1',
'$city',
'$postcode',
'',
''
)"
);
Then I want to take the id of this member user to create a mysql_query insert on the same page eg:
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
'$userid',
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
its probably a really easy answer and a really silly question but cannot seem to find the answer anywhere
thanks in advance
If I have understood correctly, and you need to get the member_id from the first query, to use in the second query, you can use the PHP function
$the_member_id = mysql_insert_id();
http://php.net/manual/en/function.mysql-insert-id.php
You can also do it without using that PHP function
$sql = "SELECT LAST_INSERT_ID()";
// add code here to run the query.
You can use the php function mysql_insert_id() to get the last id you input into the database.
EG:
$sql = "INSERT INTO `table` VALUES (NULL, 'Thomas', 'Male')";
$query = mysql_query($sql);
$id = mysql_insert_id();
So in your question after the first INSERT you need this:
$userid = mysql_insert_id();
Then your second query will work.
You can use mysql_insert_id() to get id, generated by last insert.
mysql_insert_id — Get the ID generated from the previous INSERT operation
You could use the LAST_INSERT_ID MySQL function in your second SQL statement to get the last insert ID from the first.
mysql_query("
INSERT INTO `member_orders` (
`order_id`,
`member_id`,
`date`,
`item`,
`size`,
`quantity`,
`price`,
`tracking_id`,
`status`,
`item_sent`,
`notes`
) VALUES (
NULL,
LAST_INSERT_ID(),
'',
'',
'',
'',
'',
'',
'',
'',
''
)
");
I would recommend that if you use this approach then you execute the queries within a transaction. That way there's no way that another insert can occur between your first insert and your second, thus throwing off the result of LAST_INSERT_ID.
After executing mysql_query() function you can get lastly inserted id of lastly inserted table by mysql_insert_id().
You can do something like what is done in this example
$sql = "INSERT INTO users(name,gender) VALUES ('$name','$gender')";
$result = mysql_query( $sql,$conn );
$user_id = mysql_insert_id( $conn );
$sql = "INSERT INTO website(site,user) VALUES ('$site',$user_id)";
$result = mysql_query( $sql,$conn );
Manual for mysql_insert_id

Categories