PDO Last insert ID - php

I am using $insertedId = $pdo_conn->lastInsertId(); to get the last inserted ID after an insert query then i run another insert query:
foreach ($records as $emails_to) {
$stmt = $pdo_conn->prepare("INSERT into emails_to (email_seq, email) values (:email_seq, :email) ");
$stmt->execute(array(':email_seq' => $InsertedId, ':email' => $emails_to["email"]));
}
but it doesn't seem to recognise the last insert ID, i get this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'email_seq' cannot be null'
what have i done wrong?

$insertedId and $InsertedId are not the same. Variable names are case-sensitive.

Your $insertedID doesn't match $InsertedID - case issue
edit; darn, beaten to the post

Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id.
This is an example
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");
try {
$dbh->beginTransaction();
$stmt->execute( array('user', 'user#example.com'));
$dbh->commit();
print $dbh->lastInsertId();
}
catch(PDOException $e) {
$dbh->rollback();
print "Error!: " . $e->getMessage() . "</br>";
}
}
catch( PDOException $e ) {
print "Error!: " . $e->getMessage() . "</br>";
}
?>
When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.
for more informations visit -> PHP

Related

Is there any way to fix this code to avoid error : Duplicate entry '1' for key 'PRIMARY' each time

if(isset($_POST['submit']))
{
if ($firstName&&$lastName&&$email!=""){
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= "UPDATE abonnenter SET id = (id+1)";
$conn->exec($sql);
$sql = "INSERT INTO abonnenter (id,firstname,lastname,mail)
VALUES (id,'$firstName','$lastName', '$email')";
// use exec() because no results are returned
$conn->exec($sql);
echo "Du blir nå sendt en mail når bloggen oppdateres";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
}
is the code. It Works when I have id get -1 instead of +1, but having a primary key id be listed as negative numbers seem very bad when it comes to keeping the code semantic
Made the id auto increment. and update your sql query like
$sql = "INSERT INTO abonnenter (firstname,lastname,mail)
VALUES ('$firstName','$lastName', '$email')";
Also your code is open to sql injection use pdo or prepared statement

How to turn this SQL Query into PDO Transaction without Errors

I have this SQL Query:
BEGIN;
INSERT INTO users (username, password)
VALUES('alpha', 'omega');
INSERT INTO profiles (userid, cv, website)
VALUES(LAST_INSERT_ID(),'some cv things', 'www.domain.com');
COMMIT;
And I want to use PDO instead of the MYSQL Transcation so I can pull the catched error Because I don't get it from the MYSQL Transaction, What I've tried was
$dbh->beginTransaction();
try {
$stmt = $dbh->prepare("
INSERT INTO users (username, password)
VALUES('alpha', 'omega');
INSERT INTO profiles (userid, cv, website)
VALUES(LAST_INSERT_ID(),'some cv things', 'www.domain.com');
");
$stmt->execute();
$dbh->commit();
} catch (PDOException $e) {
$dbh->rollback();
throw $e;
}
But I kept getting this Error
Uncaught PDOException: There is no active transaction . . . PDO->rollBack() #1 {main} thrown
The reocrds were INSERTed into the Table, But the error kept being shown too.
I've tried using $dbh->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE); but still got the Error message.
Then tried to remove try-catch and kept the Query with the PDO Transactions and got this Error message
Uncaught PDOException: There is no active transaction . . . PDO->commit() #1 {main} thrown
You're throwing the exception in your error handler:
catch (PDOException $e) {
$dbh->rollback();
throw $e; // <-- right here
}
That will cause the exception to keep going until it's handled, and if it's not handled it will throw a fatal error:
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().
If your exception handler is completely handling the exception you should remove that line.
you're not passing any params do it like this:
try {
$stmt = $dbh->exec('
INSERT INTO `users` (`username`, `password`)
VALUES("alpha", "omega");
');
$stmt_2 = $dbh->exec('
INSERT INTO `profiles` (`userid`, `cv`, `website`)
VALUES(LAST_INSERT_ID(), "some cv things", "www.domain.com");
');
} catch (PDOException $e) {
$dbh->rollback();
throw $e;
}
this will execute the query - you don't need to prepare because you're already escaping your strings so a simple $dbh->exec will do the trick :)

PHP PDO can't run query INSERT INTO with SELECT

I can't run INSERT INTO and SELECT queries in one statement.
Have problem with this php code:
$db = connect_db_marketlist();
if($db != null) {
$sql = "INSERT INTO items (user_id, market_table_id, price, info )"
." VALUES ('$id', (SELECT table_id FROM markets WHERE city='$city' AND market='$market'), $price, '$info')";
echo $sql; // !!! DEBUG !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
try {
$db->query($sql);
echo "OKAY: ".$db->lastInsertId();
} catch (Exception $e) {
echo "ERROR: ".$e->getMessage();
}
}
And I got error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'market_table_id' cannot be null
Error says SELECT query returns null but when I run $sql statement directly in phpmyadmin, it is working.
This is echo $sql output:
INSERT INTO items (user_id, market_table_id, price, info ) VALUES
('12345678', (SELECT table_id FROM markets WHERE city='ANKARA' AND market='MİGROS'), 22.33, 'TEST_INFO_MİGROS')
What's wrong with me? Maybe it's my db connection:
function connect_db_marketlist() {
$servername = "localhost";
$username = "marketuserdb";
$password = "pass1234";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=marketlist", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
return $conn;
}
Is it possible to run "INSERT INTO...SELECT..." query with PDO? If yes how, if no why?
P.S: It's working when I enter any integer instead of (SELECT....) query. So no problem with DB connection.
You should set connections charset to proper one in DSN like
"mysql:host=$servername;dbname=marketlist;charset=utf8mb4"
(This is for utf-8, you should set it for your tables encoding)
the var should be inside the select
This way
"INSERT INTO items (user_id, market_table_id, price, info )"
." SELECT '$id', table_id , $price, '$info'
FROM markets WHERE city= '$city' AND market='$market' ;";

update sql foreign key automatically php

I am having trouble to let foreign key updating itself, the constraint was set as on update cascade on delete cascade in phpmyadmin.
I am able to insert everything else, just the foreign key user_id appearing as null rather than updating to the correct id.
Where was my mistake? id the the table id, I know I don't need to put into the sql statement; user_id is the foreign key linked with tbl_user
Insert to database codes
try
{
$dbh = new PDO("mysql:host=localhost;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt =$dbh->prepare( "INSERT INTO tbl_details (user_id, name,address,postcode)
VALUES(:user_id,:name,:address,:postcode)");
$stmt->bindParam(':user_id',$user_id);
$stmt->bindparam(':name', $name);
........
$stmt->execute();
$dbh = null;
}catch (PDOException $e) {
$dbh = null;
print "Error!: " . $e->getMessage() . "<br/>";
print "PHP Line Number: " . $e->getLine() . "<br/>";
print "PHP File: " . $e->getFile() . "<br/>";
die();
}
Yes, its working now, I am missing this
$stmt = $auth_user->runQuery("SELECT * FROM tbl_details WHERE user_id=:user_id");
$stmt->execute(array(":user_id"=>$user_id));
Thank you #sean and #Darwin von Corax

Trace type of error mySql PDO php

I would like to trace the type of error that occurred while executing a query using PDO prepare and execute.
For example, if I had to insert email, Name, DOB, with the email requiring to be unique, instead of writing a special query to check if Email is already taken, I would like to trace the error that occurred and know the same.
You could use a try/catch block around the insert query and handle the double email in the exception handler.
$sql = "INSERT INTO `mystuff` (email, name ) VALUES (:email, :name)";
try {
$sth = $dbh->prepare($sql);
$sth->execute(array(':email' => $email, ':name' => $name));
}
catch (Exception $e) {
echo 'email already taken';
}
Of course you must configure PDO that it throws exceptions on errors.
First of all you will configure your database to put a UNIQUE KEY
ALTER TABLE yourtable ADD CONSTRAINT uniqukey_for_mail UNIQUE(email);
Then you will use PDO with ERRMODE_EXCEPTION
$bddConnect = new PDO('dsn',$user,$password);
$bddConnect->setAttribute(PDO::ATTR_ERRMOD,PDO::ERRMOD_EXCEPTION);
Then when you will update or insert datas, you will just have to wrap your query with a try/catch, and check that your error is a constraint violation
try{
$bddConnect->exec("UPDATE yourtable SET email='already in table EMAIL' WHERE
id='other id than the one that has the email'");
}catch(PDOException $e){
if(strpos('constraint violation',$e->getMessage())!==false){
echo "already taken";
}
}

Categories