Get the id of current mysql insert - php

is there anyway to get the ID of the current record I am INSERTING into the database table using php with Mysql without having to do an extra select to get the last ID?
FOr example, if my table has these columns, id, url, name
and if url consists of the domain name and current id as the query variable ex:
domainname.com/page.php?id=current_id
$sql="INSERT INTO Persons (id, url, name )
VALUES
('domainname.com/page.php?id=".**whats_the_current_id**."','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}

as far as I know, there is no 'clean' way to find the ID you are about to insert (from what I understand from your question, this is what you want to know).
Two options in my opinion, starting with the ugly one: select max(id) from Persons, increment it with one, and hope that no insert's will mess this up for you. Like I said, its ugly, and -not- reliable.
A better option would be to first insert the record with a dummy value for url, and then retrieving the just inserted row's ID with mysql_insert_id(). Then update that record with the correct url value.
You asked for a way to retrieve the id without a select query following the insert query, but like I said, I don't think this is possible.

i use mysql_insert_id() for that. it works fine.
// pseudo-ish code
$query = "INSERT something .... "
$updated = $db->run_query($query);
$id = mysql_insert_id();

your table should be like this
ID AUTO_INCREMENT
person_id VARCHAR
person_url ...
person_name ...
your post form something like
<form method="post">
<input type="hidden" name="id" value="<?php echo uniqid() ?>" />
...
</form>
the query should be like this:
$person_id = intval($_POST['id']);
$person_url = mysql_real_escape_string($_POST['url']);
$person_name = mysql_real_escape_string($_POST['name']);
mysql_query("INSERT INTO Persons (person_id, persno_url, person_name) VALUES ( {$person_id} , {$person_url}, {$person_name} )");
$ID = mysql_insert_id();

The current ID is in $_GET['id']. You should sanitize it before inserting it into your query:
$id = intval($_GET['id']);
Then, use $id in your query.

If you add classes around the first insert and then the second select. The select will work then.
<?php
class insert1{
function inserthere(){
***insert***
}
}
class select1{
function selecthere(){
***select***
}
}
$a = new insert1;
$a->inserthere();
$b = new select1;
$b->selecthere();
?>

Related

Same Auto Incremental ID Should be insert into Insert Query

I need some help from you people. I don't know It's possible or not.
In PHP, When I insert new query into Database ID value will be auto increment. I have one more variable in that Query, which is parentID.
When Run the query, parentID should be equal to the auto Incremental ID.
I tried mysqli_insert_id($conn); this function. Get last ID. Add one with that value then assign that value to parentID and then insert into database.
But Some kind of time it may be give Isolate problem. So any one guide to provide some other solution to avoid Isolate problem. Isolate means when I try to insert, I got last ID from db. Now assign that value to ParendID variable. And then I try to insert Into DB. Assume it may take few minutes. Within that few minutes some other guys may insert their own regards. That time my last ID will be differed. So I Insert with wrong parendID value.
Please any one help me to solve this problem..!!
<?php
//My connection
$last_id = $conn->insert_id; //get last ID from DB
$parent_id = $last_id + 1;
$sql = "INSERT INTO MyGuests (firstname, lastname, email, ParentID)
VALUES ('John', 'Doe', 'john#example.com', $parent_id)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
First I get LastID and then add One with that value. Then I'll insert Into DB. Instead of this method, In query itself, Directly, can give any other possible solution to assign parent ID equal to current ID of the field?
This can be done with the help of the triggers,
all you need to do is copy the new value of the id into the parentID "AFTER" insertion.
CREATE TRIGGER ins_parentID
AFTER INSERT ON MyGuests
FOR EACH ROW SET
NEW.ParentId = NEW.ID;
Code should look something like this (THIS ONE IS NOT TESTED)

get an id from a new insert php sql

I make an insert in my database and after this insert i want to get my id ( but he is auto increment ) and all the data i have on this one are not unique . I want create a folder with this id.
$reponse = $bdd->prepare(' INSERT INTO motorbike (countryMotorbike,idModel,idGarage) VALUES (?,?,?) ');
$reponse->execute(array($country,$modelid,$_SESSION['idgarage']));
mkdir('./photos_customer/'.$_SESSION['id'].', 0777, true);
I can make a select with all the params i give to create this " motorbike " but if an other one has the same params it's could fail. That's why i need to get my ID but i really don't know how to do it.
Thank you for your help.
And sorry for my bad english.
You can get the last inserted id from the lastInsertId function. Something like this:
$reponse = $bdd->prepare(' INSERT INTO motorbike (countryMotorbike,idModel,idGarage) VALUES (?,?,?) ');
$reponse->execute(array($country,$modelid,$_SESSION['idgarage']));
$id = $response->lastInsertId();

Last insert id value store to same table another specific column

i had following table and columns
Table Name = users
column = user_id, name, email, password, status, identity
i'm using following query for insert data to table users
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['name']);
$password = mysql_real_escape_string($_POST['txtPassword']);
$password = md5($password); //===Encrypt Password
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0')";
$res = mysql_query($query);
header('location:success_register.php');//Redirect To Success Page
}
what i am asking is, i want store last id to column identity also
for example: if last user_id= 10, identity also will be = 10. i mean get last id then store that id to identity column
Result will be look like this
user_id name email password status identity
5 aa aaa#ab.com **** 1 5
6 bbb bbb#ac.com **** 1 6
how to do it,?
In MYSQL, you have alternative possibility to find it, when you think last_insert_id() is not working. You may require to have SELECT privilege on INFORMATION_SCHEMA and its tables.
If you have that privileges, try the following query.
$query = "insert into users( name, email, pasword, status, identity )"
. " values( '$name', '$email', '$password', '1',"
. " ( SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES"
. " WHERE TABLE_NAME='users' and TABLE_SCHEMA=DATABASE() )"
. " )";
And, lastly, suggesting to stop using deprecated API.
Save last insert id like this:
$id = mysql_insert_id();
and use it in next insert
You are looking for:
mysql_insert_id()
mysqli_insert_id(mysqli $link)//for mysqli
PDO::lastInsertId()//for PDO
Other Approach:
if your id column is auto increment and not random then you can select the max id(everytime just after your insert query) from the users table and insert it into whatever column you want.
$id=mysql_result(mysql_query(select max(user_id)
from users),0);
Dont use mysql_ as they are depracated.*
here is what you are looking for. Select max(user_id)+1 and store it in a variable.
Now you need to pass this variable in user_id and identity parameter.
Note that even though user_id is auto increment, it will allow you to insert the new row with specified user_id
i think you can also put it like this
$lastID = MySQLI_insert_id($DBcon); //where Dbcon is your connection to your database
and then
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','$lastID')";
$res = mysql_query($query);
I think you need to insert number of rows in the table after the insert:
It may useful to you
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0',(select COUNT(*)+1 FROM users))";

How do you add the id of one record into a column on another record?

If I have two different MySQL insert functions in a document going to two different tables, how can I get the id of one record and place it in the other table?
After the first insert you can pickup the id via mysql_insert_id
tru something like this
function insert1()
{
mysql_query("INSERT .....");
return myqsl_insert_id();
}
function insert2()
{
$id1 = insert1(); // the id you want
mysql_query("INSERT ..... $id1 ");
}
you can get the last insert id by mysql_insert_id() function and then use it.
For example your first Insert query is
$insertqry1 = mysql_query("insert into tbl_name values(..,...,..)");
$lastinsertid = myqsl_insert_id();
Your second Query will be
$insertqry2 = mysql_query("insert into tbl_name(id) values('$lastinsertid')");

How do I get all the ids of the row created by one multiple row insert statement

I'm new to php. So, please forgive me if this seems like a dumb question.
Say i have a MySQL insert statement insert into table (a,b) values (1,2),(3,4),(5,6). table 'table' has a auto increment field called 'id'.
how can I retrieve all the ids created by the insert statement above?
It will be great if i get an example that uses mysqli.
You can't. I would suggest that you maintain your own ids (using guid or your own auto-increment table) and use it when you insert into the table.
But it's possible to get the auto-increment value for the last inserted using LAST_INSERT_ID():
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
AngeDeLaMort's answer is almost right. Certainly, the most appropriate way to deal with the problem is to insert one row at a time and poll the insert_id or generate the sequence elsewhere (which has additional benefits in terms of scalability).
I'd advise strongly against trying to determine the last insert_id and comparing this the most recent insert_id after the insert - there's just too may ways this will fail.
But...an alternative approach would be:
....
"INSERT INTO destn (id, data, other, trans_ref)
SELECT id, data, other, connection_id() FROM source";
....
"SELECT id FROM destn WHERE trans_ref=connection_id()";
....
"UPDATE destn SET trans_ref=NULL where trans_ref=connection_id()";
The second query will return the ids generated (note that this assumes that you use the same connection for all 3 queries). The third query is necessary because connection ids to go back into the pool when you disconnect (i.e. are reused).
C.
In some cases, if you have another identifier of sort such as a UserID, you could filter your query by UniqueID's greater than or equal to mysql_insert_id(), limit by the number of affected rows and only display those by the user. This would really only work inside of a transaction.
$SQL = "INSERT INTO Table
(UserID, Data)
VALUES
(1,'Foo'),
(1,'Bar'),
(1,'FooBar')";
$Result = mysql_query($SQL);
$LastID = mysql_insert_id();
$RowsAffected = mysql_affected_rows();
$IDSQL = "SELECT RecordID
FROM Table
WHERE UserID = 1
AND RecordID >= '$LastID'
LIMIT '$RowsAffected'";
$IDResult = mysql_query($IDSQL);
as a follow up to AngeDeLaMort:
You could seperate your inserts and do it something like this:
$data = array (
array(1,2),
array(3,4),
array(5,6)
);
$ids = array();
foreach ($data as $item) {
$sql = 'insert into table (a,b) values ('.$item[0].','.$item[1].')';
mysql_query ($sql);
$id[] = mysql_insert_id();
}
Now all your new id's are in the $id array.
Maybe I can do this
$insert = "insert into table (a,b) values (1,2),(3,4),(5,6)";
$mysqli->query($insert);
$rows_to_be_inserted=3;
$inserted_id = $mysqli->insert_id // gives me the id of the first row in my list
$last_row_id = ($inserted_id+$rows_to_be_inserted)-1;
$mysql->query("select * from table where id between $inserted_id and $last_row_id");
what to you guys say?

Categories