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
Related
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');
I have to register a costumer and/or a manager into the database. I just have one form for the information, the only difference is the ID number (valid for managers). The costumers should leave this form blank. I was trying to save the data just using an if statement (If it is blank, save the information in costumer table. If it is not, save in manager). I have not seen this on my classes so I am not sure if it is possible.
Is it possible to use an if statement to insert data? What I mean is, I have two different tables but just one form (one of the forms will make the difference for which table the data will be saved.
The data in the manager table is ok, but when I try to insert data into costumer it is not working. I am not sure that I can use this.
if($_SESSION['id'] != null){
$sql = "INSERT INTO manager (id,magname,maglname,maguser,magpass) VALUES (?, ?, ?, ?, ?);";
$sth = $DBH->prepare($sql);
$sth->bindParam(1, $_SESSION['id'], PDO::PARAM_INT);
$sth->bindParam(2, $_SESSION['firstname'], PDO::PARAM_INT);
$sth->bindParam(3, $_SESSION['secondname'], PDO::PARAM_INT);
$sth->bindParam(4, $_SESSION['username'], PDO::PARAM_INT);
$sth->bindParam(5, $_SESSION['password'], PDO::PARAM_INT);
$sth->execute();
}
if(empty($_SESSION['id']){
$sql = "INSERT INTO costumer (fisrtname,lastname,username,password) VALUES (?, ?, ?, ?);";
$sth = $DBH->prepare($sql);
$sth->bindParam(1, $_SESSION['firstname'], PDO::PARAM_INT);
$sth->bindParam(2, $_SESSION['lastname'], PDO::PARAM_INT);
$sth->bindParam(3, $_SESSION['username'], PDO::PARAM_INT);
$sth->bindParam(4, $_SESSION['password'], PDO::PARAM_INT);
$sth->execute();
}
you can do it directly through following code
if(isset($_SESSION['id']))
$sql = "INSERT INTO `manager`..."
else
$sql = "INSERT INTO `customer`..."
or something like this
if(!empty($_SESSION['id']))
{ $sql = "INSERT INTO `manager`..."}
else
{ $sql = "INSERT INTO `customer`..."}
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.
I am inserting a row into a MySQL table from PHP and running a query right after the insert to get the key value of the row that was just inserted like so:
$stmt = $this->db->prepare("INSERT INTO user(vFirstName, vLastName, vEmail, vPassword, iSkilllevelid, vTournaments, vDays, dAddedDate, eStatus) VALUES (?,?,?,?,4,'Pick-Up','Saturday',NOW(),'Active')");
$stmt->bind_param("ssss", $firstName, $lastName, $email, $pwd);
$stmt->execute();
$stmt->close();
$stmt = $this->db->prepare('SELECT iUserId FROM user WHERE vEmail=?');
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($iUserId);
while ($stmt->fetch()) {
break;
}
After this code executes, $iUserId has the correct auto incremented key value (1143 for instance), but when I actually look at the database table, the row with that key (1143) does not exist. How is that possible??
Instead of selecting from the table after insertion, you should use mysqli::$insert_id:
$stmt = $this->db->prepare('
INSERT INTO user
(vFirstName, vLastName, vEmail, vPassword, iSkilllevelid,
vTournaments, vDays, dAddedDate, eStatus)
VALUES
(?,?,?,?,4,"Pick-Up","Saturday",NOW(),"Active")
');
$stmt->bind_param('ssss', $firstName, $lastName, $email, $pwd);
$stmt->execute();
$iUserId = $this->db->insert_id;
$stmt->close();
As to why the inserted data is not appearing from other connections, it seems likely that your transaction has not been committed:
$this->db->commit();
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');