Get last insert id after a prepared insert with PDO - php

I'm using PHP PDO with PostgreSQL for a new project.
Given the following function, how can I return the id of the row just inserted?
It doesn't work the way it looks now.
function adauga_administrator($detalii) {
global $db;
$ultima_logare = date('Y-m-d');
$stmt = $db->prepare("INSERT INTO site_admins (sa_nume, sa_prenume, sa_user_name, sa_password, sa_email, sa_id_rol, sa_status, sa_ultima_logare) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bindParam(1, $detalii['nume']);
$stmt->bindParam(2, $detalii['prenume']);
$stmt->bindParam(3, $detalii['username']);
$stmt->bindParam(4, md5(md5($detalii['parola'] . SIGURANTA_PAROLE) . SIGURANTA_PAROLE));
$stmt->bindParam(5, $detalii['email']);
$stmt->bindParam(6, $detalii['rol'], PDO::PARAM_INT);
$stmt->bindParam(7, $detalii['status'], PDO::PARAM_INT);
$stmt->bindParam(8, $ultima_logare);
$stmt->execute();
$id = $db->lastInsertId();
return $id;
}

From the Manual:
Returns the ID of the last inserted
row, or the last value from a sequence
object, depending on the underlying
driver. For example, PDO_PGSQL()
requires you to specify the name of a
sequence object for the name
parameter.
It should be something like:
return $db->lastInsertId('yourIdColumn');
[EDIT] Update link to doc

From the PHP manual:
For example, PDO_PGSQL() requires you
to specify the name of a sequence
object for the name parameter.
You could also use RETURNING in the INSERT-statement and fetch the INSERT-result like a SELECT result.

Previous answers are not very clear (PDO doc too)
In postgreSQL, sequences are created when you are using the SERIAL data type.
CREATE TABLE ingredients (
id SERIAL PRIMARY KEY,
name varchar(255) NOT NULL,
);
So the sequence name will be ingredients_id_seq
$db->lastInsertId('ingredients_id_seq');

Related

Call SQL Stored Procedure from PHP PDO

I need to call a stored procedure to insert the data to sql and it return a value with output parameter
like
CREATE PROCEDURE InsertInfo
#userid VARCHAR(100),
#login_time DATETIME,
#IsSuccuess BIT,
#loginid INT OUTPUT
AS
BEGIN
INSERT INTO Audit_LoginLogoutAttempt(UserID,Login_Time, IsSuccuess, DateCreated) VALUES (#userid,#login_time,#IsSuccuess, GETDATE())
SET #loginid = ##IDENTITY
END
GO
How to send input and output parameters using PHP
$stmt = $conn->prepare("{CALL InsertInfo(?, ?, ?, ?)}");
$stmt->bindParam(1, $UserID);
$stmt->bindParam(2, $LoggedInDateTime);
$stmt->bindParam(3, $IsSuccuess);
$stmt->bindParam(4, $get_id, PDO::PARAM_INT, 32);
$stmt->execute();
echo $get_id;
I tried like this but I'm not getting desired value from $get_id
You should bind your parameter as an OUTPUT parameter. If you have output parameters in your stored procedure and stored procedure returns recordsets, you need to fetch all recordsets to get output values.
<?php
# Statement
$stmt = $conn->prepare("{CALL InsertInfo(?, ?, ?, ?)}");
$stmt->bindParam(1, $UserID);
$stmt->bindParam(2, $LoggedInDateTime);
$stmt->bindParam(3, $IsSuccuess);
$stmt->bindParam(4, $get_id, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->execute();
# Fetch results. Include this if your procedure returns resultsets (usually from SELECT statements):
#do {
# while ($row = $stmt->fetch()) {
# //
# }
#} while ($stmt->nextRowset());
# Get OUTPUT parameter value
echo $get_id;
?>
I usually put SET NOCOUNT ON as first line in stored procedures. This prevents SQL Server from passing the count of rows affected as part of the result set.
CREATE PROCEDURE InsertInfo
#userid VARCHAR(100),
#login_time DATETIME,
#IsSuccuess BIT,
#loginid INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Audit_LoginLogoutAttempt(UserID,Login_Time, IsSuccuess, DateCreated) VALUES (#userid,#login_time,#IsSuccuess, GETDATE())
SET #loginid = ##IDENTITY
END

get inserted row after doing an insert query? [duplicate]

I'm using PHP PDO with PostgreSQL for a new project.
Given the following function, how can I return the id of the row just inserted?
It doesn't work the way it looks now.
function adauga_administrator($detalii) {
global $db;
$ultima_logare = date('Y-m-d');
$stmt = $db->prepare("INSERT INTO site_admins (sa_nume, sa_prenume, sa_user_name, sa_password, sa_email, sa_id_rol, sa_status, sa_ultima_logare) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bindParam(1, $detalii['nume']);
$stmt->bindParam(2, $detalii['prenume']);
$stmt->bindParam(3, $detalii['username']);
$stmt->bindParam(4, md5(md5($detalii['parola'] . SIGURANTA_PAROLE) . SIGURANTA_PAROLE));
$stmt->bindParam(5, $detalii['email']);
$stmt->bindParam(6, $detalii['rol'], PDO::PARAM_INT);
$stmt->bindParam(7, $detalii['status'], PDO::PARAM_INT);
$stmt->bindParam(8, $ultima_logare);
$stmt->execute();
$id = $db->lastInsertId();
return $id;
}
From the Manual:
Returns the ID of the last inserted
row, or the last value from a sequence
object, depending on the underlying
driver. For example, PDO_PGSQL()
requires you to specify the name of a
sequence object for the name
parameter.
It should be something like:
return $db->lastInsertId('yourIdColumn');
[EDIT] Update link to doc
From the PHP manual:
For example, PDO_PGSQL() requires you
to specify the name of a sequence
object for the name parameter.
You could also use RETURNING in the INSERT-statement and fetch the INSERT-result like a SELECT result.
Previous answers are not very clear (PDO doc too)
In postgreSQL, sequences are created when you are using the SERIAL data type.
CREATE TABLE ingredients (
id SERIAL PRIMARY KEY,
name varchar(255) NOT NULL,
);
So the sequence name will be ingredients_id_seq
$db->lastInsertId('ingredients_id_seq');

How to perform the following insert, mysql

I have two tables, reports and events, each table has a unique identifier called id with Auto increment, the problem is that the id in each table is not the same because a report can have events but maybe not. I would like to make a double insert but one column in each table must have an unique key. I do this with the following function:
function addactioneventuser(){
try {
$this->conn->beginTransaction();
$query = "INSERT INTO
" . $this->table_name . "
SET
case_id = ?,
from_to = 0,
action_id = ?,
accepted = 0,
message = ?";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind values
$stmt->bindParam(1, $this->case_id);
$stmt->bindParam(2, $this->action_id);
$stmt->bindParam(3, $this->message);
// execute the query
$stmt->execute();
// insert event query
$query2 = "INSERT INTO event_case
SET
title = ?, body = ?, class = ?, start = ?, end = ?, case_id= ?, worker_id = ?";
// prepare query statement
$stmt = $this->conn->prepare($query2);
// bind values
$stmt->bindParam(1, $this->title);
$stmt->bindParam(2, $this->body);
$stmt->bindParam(3, $this->class_event);
$stmt->bindParam(4, $this->start);
$stmt->bindParam(5, $this->end);
$stmt->bindParam(6, $this->case_id);
$stmt->bindParam(7, $this->worker_id);
// execute the query
$stmt->execute();
$this->conn->commit();
return true;
} catch (Exception $e) {
$stmt->rollBack();
return false;
}
}
The two inserts works perfectly but my problem is that the two ids for each table are not the same and as a consequence I can not delete at the same time an specific record from both tables and I don't know how to do it. I read about Cascade and other possible solutions but none of them seem pausible for my problem. I don't mind to create another column to use it as reference for both tables but I don't know how to do it in the above query.
Thank you in advance
Last insert id is $this->conn->insert_id;
You can get it after the operation and use the identifier.
For example to add it to the desired table

Trouble Updating a Database Record

Here is prepare update statement and I think I Have the Variable types out of whack, not sure.
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE `Calibration_and_Inspection_Register` SET `item_type` = ?, `location` = ?, `date_last_test` = ?, `serial_number` = ?, `date_next_test` = ?, `comments` = ?
WHERE `id`=?"))
{
$stmt->bind_param("issdsds",`$id`, `$item_type`, `$location`, `$date_last_test`, `$serial_number`, `$date_next_test`, `$comments`);
$stmt->execute();
$stmt->close();
}
Order is important if you are not using named parameters. Since id is last parameter in the statement, it needs to be the last in the list of bound parameters as well.
Back-ticks around your parameter variables names in bind_param() call are also probably giving you errors. It should look like this:
$stmt->bind_param("ssdsdsi",$item_type, $location, $date_last_test, $serial_number, $date_next_test, $comments, $id);

How to get the row of the last insert on Oracle using PDO?

I need to get the last row that I inserted using PDO in PHP. I've been searching and I've found PDO::lastInsertId but it doesn't work on Oracle.
What alternatives I have? Other ways to do that? I think to get the current value of the sequence (in that table I use a sequence to increment the ID) using PDO but I don't know if I can.
Update 1:
Here's my code.
static function insertarProveedor($name, $address, $phone, $email) {
$con = conexionBD();
try {
$stmt = $con->prepare("INSERT INTO Proveedores (NOMBRE, DIRECCION, TELEFONO, EMAIL) VALUES (?, ?, ?, ?)
RETURNING OID_PROVEEDOR INTO :id");
$stmt->bindParam(1, $nombre);
$stmt->bindParam(2, $direccion);
$stmt->bindParam(3, $telefono);
$stmt->bindParam(4, $correo);
$stmt->bindParam('OID_PROVEEDOR', $id, PDO::PARAM_INT, 8);
} catch (PDOException $e) {
echo "Error".$e->GetMessage();
}
return $id;
}
I got the following message error:
ErrorSQLSTATE[HY093]: Invalid parameter number: mixed named and
positional parameters
Notice: Undefined variable: id in D:\xampp\htdocs\Gestor\include\inserciones.inc on line 43
The line 43 is return $id;
you can use the oracle specific returning id into var method
$query = "INSERT INTO employees (name) VALUES ('Jones') RETURNING employee_no INTO :employee_no";
$stmt = $pdo->prepare($query);
$stmt->bindParam('employee_no', $employee_no, PDO::PARAM_INT, 8);
$stmt->execute();
Then the $employee_no will have the last id.
One alternative would be to first retrieve the next value from the sequence and then use it in the insert statement.

Categories