How to get last created ID - php

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));

Related

getting last auto generated id using mysql_insert_id() in php

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']

How can I write a php code for data can not find in table of MySQL database?

I am so sorry mybe it is a silly question but as I am new in web language and php I dont know how to solve this problem.
I have a code which is getting ID from user and then connecting to MySQL and get data of that ID number from database table and then show on webpage.
But I would like to what should I add to this code if user enter an ID which is not in table of database shows a message that no data found.
Here is my code:
<?php
//connect to the server
$connect = mysql_connect ("localhost","Test","Test") ;
//connection to the database
mysql_select_db ("Test") ;
//query the database
$ID = $_GET['Textbox'];
$query = mysql_query (" SELECT * FROM track WHERE Code = ('$ID') ");
//fetch the results / convert results into an array
$ID = $_GET['Textbox'];
WHILE($rows = mysql_fetch_array($query)) :
$ID = 'ID';
echo "<p style=\"font-color: #ff0000;\"> $ID </p>";
endwhile;
?>
Thank You.
Sorry if it is so silly question.
You should use PDO (great tutorial here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ). This way, you can develop safer applications easier. You need to prepare the ID before inserting it to the query string, to avoid any user manipulation of the mysql query (it is called sql injection, guide: http://www.w3schools.com/sql/sql_injection.asp ).
The main answer to your question, after getting the results, you check if there is any row in the result, if you got no result, then there is no such an ID in the database. If you use PDO statements $stmt->rowCount();.
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM table WHERE Code=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT); // or PDO::PARAM_STR
$stmt->execute();
$row_count = $stmt->rowCount();
if ($row_count > 0) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//results are in $results
} else {
// no result, no such an ID, return the error to the user here.
}
Another reason to not use mysql_* functions: http://php.net/manual/en/migration55.deprecated.php

Get id of last inserted row in PHP

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

mysql_insert_id() not returning a value -

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...

Why does mysql_insert_id() return 0?

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;

Categories