PDO lastInsertID is returning 0 - php

I am having trouble with lastInsertID returning 0. It is working in another page, so I have something wrong here.
The following is in a try/catch block.
$idCount = "42";
/** set the database **/
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
/** set the error reporting attribute **/
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("SELECT image1 FROM items WHERE `id` = :id");
/** bind the parameters **/
$stmt->bindParam(':id', $idCount, PDO::PARAM_STR);
$stmt->execute();
$idCount = $db->lastInsertId();
echo $idCount;

The function name ->lastInsertId() should give you a hint that SELECT statements wouldn't normally set the last insert id.
Typically only INSERT statements on tables with an auto_increment column exhibit that behaviour.
There are exceptions though, such as when LAST_INSERT_ID(expr) is used:
SELECT LAST_INSERT_ID(`id`) AS `id`, image1 FROM items WHERE `id` = :id

lastInsertId() will only return the last insert id if you actually do an insert. You are only doing a select.

Related

How to get the value of expression from LAST_INSERT_ID(`my_column`+1)?

DB Type: MariaDB
Table Engine: InnoDB
I have a table where inside it has a column with a value which is being incremented (not auto, no inserting happens in this table)
When I run the following SQL query in phpMyAdmin it works just fine as it should:
UPDATE `my_table`
SET `my_column` = LAST_INSERT_ID(`my_column` + 1)
WHERE `my_column2` = 'abc';
SELECT LAST_INSERT_ID();
The above returns me the last value for the my_column table when the query happened. This query was taken directly from the mysql docs on locking: https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html (to the bottom) and this seems to be the recommended way of working with counters when you don't want it to be affected by other connections.
My PDO:
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 `my_table`
SET `my_column` = LAST_INSERT_ID(`my_column` + 1)
WHERE `my_column2` = 'abc';
SELECT LAST_INSERT_ID();";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
$result = $stmt->fetchColumn(); // causes general error
$result = $stmt->fetch(PDO::FETCH_ASSOC);// causes general error
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Exact error SQLSTATE[HY000]: General error, If I remove the lines where I try to get the result, it updates the column, but I still do not have a return result... how do I perform that update query and get the select result all in one go like I do when I run it in phpMyAdmin? This all needs to happen in one go as specified by the MySQL docs so I don't have issues where two connections might get the same counter.
There is no need to perform SELECT LAST_INSERT_ID();. PDO will save that value automatically for you and you can get it out of PDO.
Simply do this:
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8mb4", $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$sql = "UPDATE `my_table`
SET `my_column` = LAST_INSERT_ID(`my_column` + 1)
WHERE `my_column2` = 'abc'";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
$newID = $conn->lastInsertId();
lastInsertId() will give you the value of the argument evaluated by LAST_INSERT_ID().

Get duplicate entry error message and use in if statement

I would like to get the error message if a duplicate entry error happened with PDO.
this is the code I use where a duplicate entry is possible because id is a unique key:
$movetotable = $conn->prepare("INSERT INTO `$table` SELECT * FROM `$trashtable` WHERE id = :id");
$movetotable->bindParam(':id', $id, PDO::PARAM_STR);
$movetotable->execute();
I hope it is possible with PHP PDO, I know this: PDO::errorCode() but I simply don't know how to use it in an if statement.
Thanks in advance
$stmt = $conn->prepare("INSERT IGNORE INTO `$table` SELECT * FROM `$trashtable` WHERE id = ?");
$stmt->execute([$id]);
$id = $conn->lastInsertId();
if (!$id) {
echo "a dupe!";
}

PHP MYSQL SELECT Returns NULL

I executing the following code which creates a company_id as a UUID_SHORT in a temporary table.
This company_id will then be used to insert records in multiple tables with the UUID as the primary key. My issue is when I try retrieve the company_id that is $company_id in my code it is null. However if I json_encode ($tempResult) the company_id value is there. What am I doing wrong?
Any help is much appreciated, thank you!
try {
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $db->id, $db->pass); //connect to db
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //error modes
$temp = $conn->prepare('CREATE TEMPORARY TABLE tempId (user_id VARCHAR(17) PRIMARY KEY, company_id VARCHAR(17))');
$temp->execute();
$temp = $conn->prepare('INSERT INTO tempId(user_id, company_id) VALUES(:user_id, UUID_SHORT())');
$temp->bindParam(':user_id', $_SESSION['username'], PDO::PARAM_INT);
$temp->execute();
$temp = $conn->prepare('SELECT company_id FROM tempId WHERE user_id = :user_id ');
$temp->bindParam(':user_id', $_SESSION['username'], PDO::PARAM_INT);
$temp->execute();
$tempResult= $temp->fetchAll(PDO::FETCH_ASSOC);
$company_id = $tempResult->company_id;
// $result[1] =$_SESSION('username');
} catch(PDOException $e) {
$result = $e->getMessage();
}
print json_encode($company_id);
Here:
$tempResult= $temp->fetchAll(PDO::FETCH_ASSOC);
If the fetchAll is successful, then $tempResult will be an array. For debugging, we can verify this using the convenient var_dump, e.g.
var_dump($tempResult);
If $tempResult is an array, I'm wondering about this expression:
$tempResult->company_id
What does that return? What do you expect that to return? Why?
EDIT: I know better than to answer a question with a question, or three questions.
However, I can't (in good conscience) bring myself to giving an "answer" to the problem with OP code...
at least not without (figuratively) scratching my head wondering about the actual SQL being used in the code.
What is the purpose of the TEMPORARY TABLE? Why is there an INSERT to it? Why is the UNSIGNED BIGINT datatype (returned by UUID_SHORT() function) being cast to a VARCHAR(17)? Is there some reason we want to lop off 1 or 2 digits when the function returns 18 or 19 decimal digits?
If the intent of this block of code is to return a value from MySQL UUID_SHORT() function, I'm not understanding why we need more than one statement. Obviously, there's something I'm missing, why this wouldn't suffice:
try {
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $db->id, $db->pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare('SELECT UUID_SHORT() AS company_id');
$sth->execute();
$company_id = $sth->fetchColumn();
} catch(PDOException $e) {
//var_dump($e->getMessage);
} finally {
if(isset($sth)){ $sth->close(); }
if(isset($conn)){ $conn->close(); }
}
(An application wouldn't churn database connections like this; there would either be a connection pool, or the connection would be passed in to this routine.)
Not sure, but as soon as fetchAll returns array, your code:
$company_id = $tempResult->company_id;
is invalid, you should:
$company_id = $tempResult[0]['company_id'];
or
$tempResult= $temp->fetch(PDO::FETCH_ASSOC);
$company_id = $tempResult['company_id'];

run insert query once only when the database is created php pdo

from config.php
<?php
global $dbh;
$dbname = 'memberdb';
try {
$dbh = new PDO("mysql:host=localhost", "root", "");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbname = "`".str_replace("`","``",$dbname)."`";
$dbh->query("CREATE DATABASE IF NOT EXISTS $dbname");
$dbh->query("use $dbname");
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql ="CREATE TABLE IF NOT EXISTS $member (
mem_id int(40) NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(40) NOT NULL,
password VARCHAR(40) NOT NULL);" ;
$dbh->exec($sql);
$stmt = $dbh->prepare("INSERT INTO member (username, password) VALUES (?,?)")or die($db->errorInfo());
$stmt->bindValue(1,"admin1",PDO::PARAM_STR);
$stmt->bindValue(2,"password1",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin2",PDO::PARAM_STR);
$stmt->bindValue(2,"password2",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin3",PDO::PARAM_STR);
$stmt->bindValue(2,"password3",PDO::PARAM_STR);
$stmt->execute();
} catch(PDOException $e) {
}
?>
This is my function of new user when the user is registered using a registered button.
How to make this kind of function run only one, when the database is created and only.
I will need to put defined value for each input but i didnt not change it yet
UPDATE
The code i used is above my prob is still the same when i reload the index.php the query runs again making double entry..what i want is that when the database is create the query will run and when loaded the database is not created again so i want the query to not run again to avoid double entry.
$stmt = $dbh->prepare("SELECT * FROM member") ;
$stmt->execute();
$count = $stmt -> rowCount();
echo $count;
if( $count == 00 ){
$stmt = $dbh->prepare("INSERT INTO member (username, password) VALUES (?,?)")or die($db->errorInfo());
$stmt->bindValue(1,"admin1",PDO::PARAM_STR);
$stmt->bindValue(2,"password1",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin2",PDO::PARAM_STR);
$stmt->bindValue(2,"password2",PDO::PARAM_STR);
$stmt->execute();
$stmt->bindValue(1,"admin3",PDO::PARAM_STR);
$stmt->bindValue(2,"password3",PDO::PARAM_STR);
$stmt->execute();
}
i only have one more question why is it sometimess the echo for count is 3 and sometimes its 33 its like the query is run twice please clear this out...this worked but maybe just maybe there are incorrect logic here please feel free to edit to make it perfect.

retrieve the id PDO if a value already exists

I have two tables which are linked with many many relationship,Normally I work with Mysqli for querying,but now for some reasons I have to use PDO,So my problem is 1st to check if a value doesn't exists, to add it in a table tag,and if not to take the id of the value and add the related data in the join data.
tag-tagmap-post a tag can belong to many posts,and a post can have many tags I try this but when a tag name already exists I can't retrieve the id of the tag.
$sql = "
INSERT INTO tag (name)
SELECT * FROM (SELECT :name) AS tmp
WHERE NOT EXISTS (
SELECT name FROM tag WHERE name =:name
) LIMIT 1";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(":name", $post->name);
$stmt->execute();
$test=$post->id = $db->lastInsertId();
$db = null;
//echo json_encode($post);
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
$sql2="INSERT INTO tagmap (tag_id,post_id,user_id) VALUES(:id2,:post_id,:id)";//
try {
$db = getConnection();
$stmt = $db->prepare($sql2);
$stmt->bindParam("id2", $test);//tag id
$stmt->bindParam("post_id", $post->post_id);//post_id
$stmt->bindParam("id", $id);
$stmt->execute();
//$post2->id = $db->lastInsertId();
$db = null;
echo json_encode(array("result"=>$test));
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
Thank you for your help!!!
As documented under PDO::prepare():
You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.
That said, the insertion query itself is over-complicated (and contains syntax errors: there is no LIMIT clause in the INSERT syntax). You could instead:
define a UNIQUE key over (name) in the tag table:
ALTER TABLE tag ADD UNIQUE (name);
use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO tag (name) VALUES (?)
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id);
This will ensure that $db->lastInsertId() returns the ID of the relevant record whether it has been newly inserted or it already existed.

Categories