如何使用 PDO 从 MySQL 获取数字类型? [英] How to get numeric types from MySQL using PDO?

查看:19
本文介绍了如何使用 PDO 从 MySQL 获取数字类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PDO 和 MySQL,出于某种原因,当从数据库中获取 int 类型的值时,PDOStatement 返回的是数字的字符串表示形式,而不是数字类型的值.我如何防止这种情况发生?

我注意到 PDO 类有一个属性:PDO::ATTR_STRINGIFY_FETCHES 应该解决这个问题,但是当试图修改它时,它抛出一个错误,说该属性不是对 MySQL 驱动有效.

在查询数据库时得到字符串而不是数字是否正常?

解决方案

我不认为在 PHP 5.2 中可以有数字":-(

在 PHP 5.3 中,如果我没记错的话,当您使用新的 (PHP 中的新 >= 5.3) mysqlnd (MySQL 本地驱动程序) 驱动程序.

好吧,在对我的书签进行更多挖掘之后,我发现了这篇关于 mysqlnd 的文章:PDO_MYSQLND:PHP 5.3 中 PDO_MYSQL 的新特性

上面写着(引用):

<块引用>

使用mysqlnd进行PDO的优势

mysqlnd 在以下情况下返回本机数据类型使用服务器端准备好的语句,例如返回一个 INT 列作为整数变量而不是作为细绳.这意味着更少的数据内部转化.

但这仅适用于 PHP 5.3(前提是您的 PHP 5.3 版本是使用 mysqlnd(而不是旧的 libmysql)编译的),并且似乎仅适用于准备好的语句:-(>

对不起...

一个解决方案是在 PHP 端有一个映射系统 (就像一个 ORM——见 Doctrine ;就像 ORM 的一个例子:我不知道它是否能满足你的要求) 将来自 DB 的结果转换为 PHP 数据类型......>

是的,如果你想使用像 ===!== 这样的操作符,这很糟糕,它们是类型敏感的...

I'm using PDO and MySQL, for some reason when getting values from the database that are int type, the PDOStatement is returning a string representation of the number and not a value of numeric type. How do I prevent this from happening?

I noticed there is a attribute of the PDO class: PDO::ATTR_STRINGIFY_FETCHES that is supposed to take care of this but, when trying to modify it, it throws an error saying the attribute is not valid for MySQL driver.

Is it normal to get strings instead of numbers when consulting a database?

解决方案

I don't think having "numbers" can be done in PHP 5.2 :-(

In PHP 5.3, it becomes possible, if I remember correctly, when you are using the new (new as in PHP >= 5.3) mysqlnd (MySQL Native Driver) driver.

Well, after more digging through my bookmarks I found this article about mysqlnd : PDO_MYSQLND: The new features of PDO_MYSQL in PHP 5.3

It says this (quote) :

Advantages of using mysqlnd for PDO

mysqlnd returns native data types when using Server-side Prepared Statements, for example an INT column is returned as an integer variable not as a string. That means fewer data conversions internally.

But this is PHP 5.3 only (provided your version of PHP 5.3 is compiled with mysqlnd (and not old libmysql)), and seems to only be the case for prepared statements :-(

Sorry...

A solution would be to have, on the PHP-side, a mapping-system (like an ORM -- see Doctrine ; just as an example of ORM : I don't know if it does what you're asking) to convert results coming from the DB to PHP datatypes...

And yes, this is bad if you want to use operators like === and !==, which are type-sensitive...

这篇关于如何使用 PDO 从 MySQL 获取数字类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆