I use PHP for server side scripting and mysql server for database.
If I use mysql_insert_id() then it gives "0" and use of LAST_INSERT_ID() causes error "object returned empty description".This error I see when I debug on client-side in objective-C.
My table's id column is auto generated. I dont' pass id explicitly.
Below is the PHP code :
// Connect to our database
$db = Frapi_Database::getInstance();
$sql = "INSERT INTO userTrip
(userId, fromLat, fromLon, fromLoc, fromPOI,
toLat, toLon, toLoc, toPOI,
tripFinished, isMatched, departureTime, createdAt)
values
(".$userId.",".$fromLat.",".$fromLon.", GeomFromText('POINT($fromLat $fromLon)')".",'".$fromPOI."',".$toLat.","
.$toLon.", GeomFromText('POINT($toLat $toLon)')".",'".$toPOI."',0,0,'".
$departureTime."','".date('Y-m-d H:i:s')."')";
$stmt = $db->prepare($sql);
if (!$stmt->execute())
throw new Frapi_Error('ERROR_INSERTING_RECORD');
$lastId = LAST_INSERT_ID();
$this->data['tripId'] = $lastId;
$db = null;
Frapi Database extends from PDO, so you would use this:
$lastId = $db->lastInsertId();
See also: PDO::lastInsertId()
Try this (if you use mysqli):
$db->insert_id;
Or (if you use PDO):
$db->lastInsertId();
are you looking for this ?
to get the last inserted id
mysql_insert_id();
mysql_insert_id
Try with
$id = mysql_insert_id();
it will work for you,try this link mysql_insert_id
and this
If your table have AUTO INCREMENT column like UserID,Emp_ID,.. then you can use this query to get last inserted record
SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name)
In PHP code:
$con = mysqli_connect('localhost', 'userid', 'password', 'database_name');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name)";
$result = mysqli_query($con, $sql);
Then you can use fetched data as your requirement
Related
I am trying to get last auto incremented customer ID from customer table using mysql_insert_ID function and store it in a variable named lastid and try to send lastid variable using session on another page and printing it there it won't give any output or error
//---page1.php
// Start a session to be able to store SESSION variables.
session_start();
// Your connection to Database
$conn = new mysqli("localhost", "my_user", "my_password", "world");
// Your insert query
$insert_query = "INSERT INTO customers .....";
// Query the database
$conn->query( $insert_query );
// STORE Last_inserted_id into $lastid and $_SESSION
$_SESSION['lastid'] = $lastid = $conn->insert_id;
//---page2.php
// Start a session to be able to use SESSION variables in the new page.
session_start();
// Get value from $_SESSION
echo $_SESSION['lastid'];
Taken from documentation $insert_id and session_start()
PDO is the one way to do this if you want to do with PDO then here you can follow this:
After a successful query simply use lastInsertId method with your PDO instance :
$lastId = $pdo->lastInsertId(); //This variable will store last insert ID
For More details about lastInsertId() Method you may check this official Documentation PHP Last Insert Id
If you think that will be better to use mysqli for you Then
Just simply after a successful query do like this:
$lastId = $mysqli->insert_id; // this is how you will get last inserted id
You may follow this stackoverflow question: Follow This
Since you're familiar with mysql, use mysqli... in that case:
$sql = "SELECT max(id) as max FROM table";
From there:
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$maxID = $row['max']
If you wish to stay in mysql_
$sql = "SELECT max(id) as max FROM table";
From there:
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$maxID = $row['max']
No matter what I try - I cant seem to pull the last created id of the query I inserted to mySql.
I read here about syntaxes that are deprecated and all sort of code that wont work.
I tried both functions (I use bigint) so I understand that this is how to go:
if (($result = $conn->query("SELECT LAST_INSERT_ID()")) === FALSE) {
die(mysql_error());
}
if ($result->fetch_assoc()) {
$id = $row[0];
echo $id;
}
but nothing!!
Can someone please just give me a full simple php code sample of how to do it?
You can use $result = $conn->insert_id; to know last inserted row
Try this to get the last insert Id,
echo mysql_insert_id();
Dont use mysql its depricated, instead use mysqli or PDO. To get last inserted record use mysqli_inserted_id(). The following shows the snipped how to use-
<?php
$link = mysqli_connect("localhost", "username", "password", "dbname") or die('Facing some problem connecting with database');
$query = "INSERT INTO `table_name` VALUES (v1, v2, v3...vn)";
mysqli_query($link, $query);
printf ("New Record with id %d inserted", mysqli_insert_id($link));
I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
http://php.net/manual/en/function.mysql-insert-id.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...
When I run this code
$sql_select = "INSERT INTO `database`.`table`(Columns) VALUES (Values)... ";
$mysqlid = mysql_insert_id($sql_select->db);
echo ($mysqlid);
I get the error message
mysql_insert_id(): supplied argument is not a valid MySQL-Link
I have tried this variation;
$mysqlid = mysql_insert_id();
echo ($mysqlid);
but that returns a 0 which, according to the documentation, means an auto_increment field was not found. The only thing I can think of is that I am not calling the auto_increment column in the $sql_select, but there is an auto_increment column in there; will that affect the behavior of mysql_insert_id?
you need to actually run the query first:
$sql= "INSERT INTO `database`.`table`(Columns) VALUES (Values)...";
$result = mysql_query($sql);
and then after that:
$id = mysql_insert_id();
echo $id
Let me know if you have still problems.
That is because $sql_select->db is not a valid MySQL Link
What you are looking for is something like this:
$sql_select = "INSERT INTO `database`.`table`(Columns) VALUES (Values)...
$result = mysql_query($sql_select);
$mysqlid = mysql_insert_id($result->db);
$result is a valid MySQL resource.
Also don't forget to have created a mysql connection
NOTE: While I used code for the original MySQL driver it's use is discouraged. Instead you want to use MySQLi or PDO_MySQL
You need to run your query:
if($result = mysql_query($sql_select)){
$mysqlid = mysql_insert_id();
echo $mysqlid;
}
Cheers
your connection of mysqli is an object...so try this....
$mysqli = new mysqli("localhost", "user", "password", "dbname");
after inserting try this..
echo $mysqli->insert_id;
Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?
<?php
$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());
$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";
?>
Use this: http://php.net/manual/en/function.mysql-insert-id.php
Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.
The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.
$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");
print mysql_insert_id();
There is builtin support for it, mysql_insert_id() or something.