简体   繁体   English

PHP PDO lastInsertId返回字符串而不是整数

[英]PHP PDO lastInsertId returns string instead of integer

I'm currently building a symfony/doctrine app and one model has the following structure: 我目前正在构建一个symfony / doctrine app,一个模型具有以下结构:

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

This correctly maps to the database as: 这正确地映射到数据库:

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

So we are safe there. 所以我们在那里很安全。

Then when trying to create a new record the code goes: 然后,在尝试创建新记录时,代码会:

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

The last line is the problematic. 最后一行是有问题的。 The session_id field gets filled in with the last identity value but as a string!! session_id字段使用最后一个标识值填充,但作为字符串!

So at first, I thought doctrine was the culprit, but then debugging the code, I found out that it seems that PDO is actually the one that is returning the value as a string. 所以起初,我认为学说是罪魁祸首,但随后调试代码,我发现PDO似乎实际上是将值作为字符串返回的那个。 The method that gets called is: 被调用的方法是:

dbh->lastInsertId()

So the obvious question is: how can I solve this? 所以显而易见的问题是: 我该如何解决这个问题呢? . I found these things in the internet but haven't tried them yet: 我在互联网上发现了这些东西,但还没有尝试过:

  1. PDO::ATTR_STRINGIFY_FETCHES. PDO :: ATTR_STRINGIFY_FETCHES。 Will this work? 这会有用吗? If yes, how can I configure that? 如果是,我该如何配置?
  2. Using mysql native driver instead of pdo. 使用mysql本机驱动程序而不是pdo。 However doctrine handles it so I'm not sure if I can even configure that. 然而,学说处理它所以我不确定我是否可以配置它。
  3. The other obvious workaround is to typecast to int : (int)$session->session_id. 另一个明显的解决方法是将类型转换为int:(int)$ session-> session_id。 But that's just plain ugly as it should return an integer value (that's the whole purpose of using pdo and doctrine!) and all the other models would have the same issue. 但这只是简单的丑陋,因为它应该返回一个整数值(这是使用pdo和doctrine的全部目的!)而所有其他模型都会有同样的问题。
  4. What would be the best solution for this? 什么是最好的解决方案?

You may want to use conversion function see php manual . 您可能想要使用转换功能, 请参阅php手册

$myInteger = intval($myString)

In order to send an exception if the string represents a too high number to be converted into an integer (and avoid some nasty intermittent bugs in your code), please surround with this code : 如果字符串表示要转换为整数的数字太高而发送异常(并避免代码中出现一些令人讨厌的间歇性错误),请使用以下代码进行处理:

$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!')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM