PHP PDO lastInsertId returns a string instead of an integer

I am currently creating a symfony / doctrine application, and one model has the following structure:

Session:
  columns:
    session_id:
      type: integer(8)
      primary: true
      autoincrement: true
    session_number:
      type: string(30)

This correctly displays the database as:

CREATE TABLE `session` (
  `session_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `session_number` varchar(30) NOT NULL,

So we are safe.

Then, when trying to create a new record, the code occurs:

$newSession = new Session();
$newSession->session_number = session_id();
$newSession->save();
//...
echo $newSession->session_id; //<------ this will return a string '1'

The last line is problematic. The session_id field is populated with the last authentication value, but as a string !!

So, at first I thought the doctrine was the culprit, but then, while debugging the code, I found that, apparently, PDO is the one that returns the value as a string. The method is called:

dbh->lastInsertId()

So the obvious question is: how can I solve this? . I found these things on the Internet, but have not tried them yet:

  • PDO :: ATTR_STRINGIFY_FETCHES. Will this work? If so, how can this be configured?
  • mysql pdo. , , .
  • int: (int) $session- > session_id. , ( pdo doctrine!) .
  • ?
+3
1

. php.

$myInteger = intval($myString)

, , ( ), :

$myInteger = intval($myString)
if ($myInteger === PHP_INT_MAX) { // PHP 4.4.0 & 5.0.5 min
      throw new Exception('Integer out of range, please call your developer for bug fixing!')
}
0

Source: https://habr.com/ru/post/1773176/


All Articles