使mysql_fetch_assoc自动检测返回数据类型? [英] Make mysql_fetch_assoc automatically detect return data types?

查看:498
本文介绍了使mysql_fetch_assoc自动检测返回数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中使用mysql_fetch_assoc时,如何让它返回正确的数据类型?现在它似乎将一切都转换为字符串,我宁愿如果它离开Ints作为Ints,并以某种方式指定的日期/时间作为对象或某种不同于字符串。

When using mysql_fetch_assoc in PHP, how can I make it return the correct data types? Right now it appears to convert everything to strings, I'd prefer if it left the Ints as Ints, and somehow designated the Date/Time as either Object or somehow different than strings.

这样做的原因是我使用PHP作为Flex应用程序的后端,并且Flex有一些功能,如自动检测返回类型,如果一切都以字符串形式存在,那么它们不会工作。 p>

The reason for this is that I am using PHP as a backend to a Flex application, and Flex has some features such as automatically detecting return types, which don't work that well if everything comes in as a string.

推荐答案

我认为一个好的策略是通过编程来确定表中每个列的数据类型,并相应地投射返回的结果。这将允许您以更一致和简单的方式与数据库交互,同时仍然为您提供您需要的变量存储正确的数据类型的控制。

I think a good strategy here is to programatically determine the datatype of each column in a table, and cast the returned results accordingly. This will allow you to interact with your database in a more consistent and simple manner while still giving you the control you need to have your variables storing the correct datatype.

一个可能的解决方案:您可以使用mysql_fetch_field()获取一个包含表列的元数据的对象,然后将字符串转换回所需的类型。

One possible solution: You could use mysql_fetch_field() to get an object that holds meta-data about the table column and then cast your string back to the desired type.

//run query and get field information about the row in the table
$meta = mysql_fetch_field($result, $i);

//get the field type of the current column
$fieldType = $meta->type

一个完整的例子可以在这里找到: http://us2.php.net/manual/en/function.mysql-fetch-field.php

A full example can be found here: http://us2.php.net/manual/en/function.mysql-fetch-field.php

由于PHP松散

如果使用OO(面向对象)技术,您可以在setter中创建一个具有此功能的类()方法,因此您不必具有重复的代码。

If you are using OO (object-oriented) techniques, you could create a class with this functionality in the setter() methods so you don't have to have duplicate code.

这篇关于使mysql_fetch_assoc自动检测返回数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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