PHP & mySQL obtaining last insert ID - php

I'm quite new to this php/mysql deal and I'm having a hard time figuring out this situation particularily.
I have two tables, one of them is "dog" table and the other one is the "date" table. In order to insert a record in the "dog" table I MUST first insert a date in the "table" date and get the autoincrement id from that date.
Problem is that I've tried reading several posts on how to get the last insert id from a table you just inserted a record on and I can't seem to make it work.
$sql1="INSERT INTO FECHAS (fecha) VALUES (NOW())";
mysql_query($sql1);
echo $sql1;
$sql3="SELECT LAST_INSERT_ID()";
mysql_query($sql3);
echo $sql3;
$sql2="INSERT INTO PERRO (nombre_perro,FECHAS_id_fecha) VALUES ('$nombre_perro_var', '$last_id')";
echo $sql2;
if (!$mysqli->query($sql2)) {
echo 'Error: ', $mysqli->error;
}
$result2 = mysql_query($sql2);
Please forgive this code, I'm new and learning.
Thanks!

Use mysqli instead of mysql_
Connecting with mysqli:
$connection = mysqli_connect($hostname, $username, $password, $database_name);
Inserting into a table:
mysqli_query($connection, $sql);
Retrieving last inserted id:
$id = mysqli_insert_id($connection);

**Database**
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
**Example (MySQLi Object-oriented)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
***$last_id = $conn->insert_id;***
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
**Example (MySQLi Procedural)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
***$last_id = mysqli_insert_id($conn);***
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
**Example (PDO)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
***$last_id = $conn->lastInsertId();***
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

A procedural solution (although it might be slightly wrong - I'm terrible at PHP)...
<?php
include('path/to/connection/stateme.nts');
$query = "
INSERT INTO fecha (fecha) VALUES (NOW());
";
mysqli_query($db,$query);
$query = "
INSERT INTO perro (nombre_perro,id_fecha) VALUES (?,?);
";
$nombre_perro = 'rover';
$id_fecha = mysqli_insert_id($db);
$stmt = mysqli_prepare($db,$query);
mysqli_stmt_bind_param($stmt, 'si', $nombre_perro,$id_fecha);
mysqli_stmt_execute($stmt);
?>
You might consider binding both queries into a transaction, so that in the event that the second query fails for some reason, then the first query fails too.

Related

insert into data mysql database using php function

function inseartinto()
{
$DEL_LOG_REP = $connection->prepare("DELETE FROM test WHERE itemname='111'")$DEL_LOG_REP->execute()$DEL_LOG_REP->close()return $DEL_LOG_REP
}
This is short tutorails on connection in insert query into php...
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
For more better understand..go to http://www.w3schools.com/php/default.asp
What code are you trying to writing man..
This is not a valid code for just not insert but also for connetion..
ya go onto W3School.com as mention by #Sasa.D... it provide you with knowledge from basic to expertise..

php- get last insert id

I know this question has been answered many times. I tried a few of the solutions from here but nothing worked. I'm not using any PHP framework.
I have an insert operation taking place and I want to get the id of the inserted row.
Here's my code:
$qry="INSERT INTO tablename(content) VALUES('".$content."')";
setData($qry);
setData() is a user defined function which does insert operation.
//for data submit
function setData($qry)
{
$obj=new DBCon();
$res=$obj->submitQuery($qry);
return $res;
}
//fetches result
function getData($qry)
{
$obj=new DBCon();
$res=$obj->selectQuery($qry);
return $res;
}
This is the class I made for establishing database connectivity:
class DBCon
{
private function getConnection()
{
// hostname, username, password, database
$con=mysqli_connect("localhost","root","","dbname")OR die('Could not Connect the Database');
return $con;
}
public function closeCon()
{
mysqli_close($con);
}
public function submitQuery($qry)
{
$result=0;
$con=$this->getConnection();
$result=mysqli_query($con,$qry);
return $result;
}
public function selectQuery($qry)
{
$con=$this->getConnection();
$res=mysqli_query($con,$qry);
return $res;
}
}
To obtain the last inserted id, I wrote the following query but it did not yield any result:
SELECT LAST_INSERT_ID() FROM tablename
Is there any other method to get this?
LAST_INSERT_ID() only returns values that have been auto-generated by the MySQL server for an AUTO_INCREMENT column; when you insert a specific value, no auto-generation takes place and no value will be returned by LAST_INSERT_ID().
Try : $con->insert_id;
Try This way.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('First Name', 'Last Name', 'first#example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
MySQLi Object-oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
$last_id = $conn->insert_id;

Simple insert into database doesn't work

I have a very simple bit of code to insert data into database.
It doesn't work. I do not get any error except cannot insert. I could connect to the database so that is not the issue.
The database has 3 fields, emailadd is the 2nd field. The other 2 are auto increment id and creation date, so also a field that on add, it will add current timestamp.
$inquiry = "INSERT INTO subscribe (emailadd) VALUES ('$myemail')";
$res = mysql_query($inquiry) or die("cannot insert");
$inquiry = "INSERT INTO `subscribe` (`emailadd`) VALUES ('$myemail')";
$res = mysql_query($inquiry,$con) or die('Not Inserted : ' . mysql_error());
Some time we need $con variable to identify the database connection, let see more check here
the mysql_query is deprecated, you need to use mysqli like so :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>

return last inserted id doesn't work in php

$result = $db->query("INSERT INTO post_items(`post_id`,`content`,`date`,`user_id`,`category_id`)
VALUES ('', '".$content."', '".$date."', '".$user_id."', '".$category_id."')");
if($result) {
echo mysql_insert_id();
}else{
echo "Something is wrong. Insert failed..";
}
my post_id is an auto increment field. It gave me a '0' instead of the last inserted id.
In case your query really worked (please verify that...) you're probably mixing the outdated mysql connector and the mysqli connector. mysql_insert_id() is the function from the mysql connector. Use mysqli_insert_id() instead.
Try
if($result) {
echo $db->insert_id;
}else{
echo "Something is wrong. Insert failed..";
}
Database
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
last inserted ID:
-------------------------------------------------------------------
1. Example (MySQLi Object-oriented)
-------------------------------------------------------------------
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
-------------------------------------------------------------------
2. Example (MySQLi Procedural)
-------------------------------------------------------------------
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
-------------------------------------------------------------------
3. Example (PDO)
-------------------------------------------------------------------
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Don't include post_id when inserting a new row since it is auto_increment.

return last inserted auto-increment id php

I didn't insert any value but autocrement one of the column, how could I get the last inserted id value?
I used echo mysql_insert_id(); but I gave me '0' which isn't seem correct.
mysql_insert_id() will work only when you insert the data into table.
Database
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
last inserted ID:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

Categories