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

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

问题描述

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

我注意到有一个PDO类的属性:PDO::ATTR_STRINGIFY_FETCHES应该可以解决这个问题,但是在尝试修改它时,它抛出一个错误,指出该属性对MySQL驱动程序无效.

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

解决方案

我认为在PHP 5.2中无法实现数字" :-(

在PHP 5.3中,如果我没记错的话,当您使用新的(在PHP> = 5.3中是新的)时,就有可能使用 mysql nd (MySQL本机驱动程序)驱动程序.

好吧,在进一步浏览了我的书签之后,我发现了有关mysqlnd的文章: PDO_MYSQLND: The new features of PDO_MYSQL in PHP 5.3

它是这样的(引号):

将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天全站免登陆