Forum Moderators: coopster
I am trying to use the mysql_insert_id(); to obtain the value of the last (AUTO_INCREMENT) value for (in my case) the id field. What i am doing is separating a form into two peices. The first page collects the 1st set of data and the second page adds on with more information for the same record. When the first page is submitted, the sql query is to INSERT into table...on the second page, the sql query is to UPDATE table...
The problem I am having is that the UPDATE command actually creates a new row and doesnt actually update the existing row created from the first page INSERT. I am using a WHERE statement to specify the last_ insert_id. WHERE id='".(int)$_SESSION['last_insert_id']."'";
Any ideas as to why its creating two rows as opposed to just one?
Here is the code snippet i am using:
********************************************************************
<?php
session_start();
$_SESSION['last_insert_id'] = mysql_insert_id();
include ("/db.php");
mysql_connect("$db_ip","$db_user","$db_pass");
mysql_select_db("$db_name");
$_SESSION['firstname'] = mysql_real_escape_string($_POST['firstname']);
$_SESSION['lastname'] = mysql_real_escape_string($_POST['lastname']);
$sql = "UPDATE table SET firstname='".$_SESSION['firstname']."', lastname='".$_SESSION['lastname']."' WHERE id='".(int)$_SESSION['last_insert_id']."'";
I think it can only retrieve last insert id if you do INSERT in the same request, and you have to connect to DB prior to using mysql_insert_id.
So you have to store last insert insert id into session after INSERT operation. Like this:
mysql_query("INSERT INTO mytable (product) values ('kossu')");
$_SESSION['last_insert_id'] = mysql_insert_id();
after that you'll be able to use it wherever you need.
*****R.PHP****
<?php
session_start();
if (isset($_POST['submit']))
{
include ("/db.php");
$ru = mysql_real_escape_string($_POST['username']);
$rp = mysql_real_escape_string($_POST['password']);
$sql = "INSERT INTO users (username,password) VALUES ('$ru','$rp')";
mysql_query($sql) or die("SQL: $sql<br />".mysql_error());
$_SESSION['last_insert_id'] = mysql_insert_id();
include ("/rf.php");
exit;
}
?>
****RF.PHP*****
<?php
session_start();
if (isset($_POST['submit']))
{
include ("/db.php");
$_SESSION['r_firstname'] = mysql_real_escape_string($_POST['firstname']);
$sql = "UPDATE users SET
firstname='{$_SESSION['r_firstname']}'
WHERE id='{$_SESSION['last_insert_id']}'";
mysql_query($sql) or die("SQL: $sql<br />".mysql_error());
?>