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']
Related
I'm sorry about my PHP skills, but I'm just not figuring out how to do this simple task which is INSERT a new row and save its ID into a variable.
Here's what I got:
// mysql inserting a new row
$sql = "INSERT INTO `order` (orderTitle, orderDescription, orderPrice,userID, categoryID)
VALUES('$title', '$description','$price','$userID','$category');";
$sql .= "SELECT LAST_INSERT_ID();";
$result = mysqli_multi_query($con,$sql);
$result_get_id= mysqli_next_result($con);
$row = mysqli_fetch_row($result_get_id);
$order_id = $row[0]; // <-- how to get this value??
I realized row[0] doesn't work, which is why I would like to know how to extract the LAST_INSERT_ID() value correctly.
A couple of things here...
Don't use mysqli_multi_query - it's unnecessary in your example. Use mysqli_query on the INSERT only. No need to query last insert id in SQL.
To get the last insert id, call mysqli_insert_id directly after your INSERT query. You can assign this to a variable, such as $order_id = mysqli_insert_id();
The database class you're using has built in functions for this e.g. mysqli_insert_id(), or for PDO $db->lastInsertId().
$mysqli->query("INSERT INTO order ... ");
printf ("Primary key of new record: %d.\n", $mysqli->insert_id);
http://php.net/manual/en/mysqli.insert-id.php
I'm inserting into an Access database via PHP but I'm struggling to get the ID of the last inserted row. I have had this working previously but our server broke and I've had to re-write it, but it doesn't return - I'm sure this is how I did it:
$idquery = "select ##IDENTITY from [Businesses]";
try{
$rs = $conn->execute($query);
$idReturned = $conn->execute($idquery);
echo json_encode($idReturned);
} catch(com_exception $e){
echo($e);
}
The insert is successful but the json_encode($idReturned); is blank, any idea why?
Are you using PDO?
If you are, you can do the following:
$id = $con->lastInsertId();
<?php
// Assume $dbh connection handle is already established
$sql = "INSERT INTO business (name) VALUES ('BUS')";
$sth = $dbh->prepare($sql);
$sth->execute();
$lastId = $dbh->lastInsertId(); //This is where you get last inserted ID
?>
Depends on the DB provider, there might be a situation that you need to set the "Primary key" for that table
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));
Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);
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