[英]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: 我在互联网上发现了这些东西,但还没有尝试过:
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.