获取 MySQL 查询结果作为其本机数据类型?

发布于 2024-08-24 11:30:55 字数 154 浏览 2 评论 0原文

我尝试使用 mysql_fetch_row() 和 mysql_result() 获取 MySQL 查询结果,并且数值以字符串形式返回。

有什么方法可以获取表中存储的数据类型的数据吗?

该应用程序将查询许多不同的查询,因此我无法将值一对一地转换为预期的数据类型。

I have tried fetching MySQL query results using mysql_fetch_row() and mysql_result() and numeric values are being returned as strings.

Is there any way to fetch the data as its datatype stored in the table?

The application will be querying many different queries so I will be unable to cast the values as the intended datatype on a 1 by 1 basis.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

丿*梦醉红颜 2024-08-31 11:30:55

我不认为在 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)),并且似乎仅适用于准备好的语句

:-(我想,在你的情况下,很有帮助......

这是另一篇,仍然是关于 mysqlnd 的新功能,它不仅讨论了准备好的语句:PHP:使用 mysqlnd 节省新的网络流量、CPU 和内存

不过,不确定这是否已合并到官方 mysqlnd 驱动程序中 - 最好的方法是尝试;但无论如何,它仍然只是 PHP >= 5.3...

另一个解决方案是在 PHP 端使用某种映射系统(例如 ORM)来将来自数据库的结果转换为 PHP 数据类型......

是的,这就是如果您想使用像 ===!== 这样类型敏感的运算符,那就不好了......

I don't think getting data in their native datatypes (i.e. anything else that strings) 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.

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 the old libmysql)), and seems to only be the case for prepared statements :-(

Which doesn't quite help, in your situation, I guess...

And here's another one, still about the new features of mysqlnd, which talks about this for not only prepared statements : PHP: New network traffic, CPU and memory savings with mysqlnd.

Not sure this has been merged into the official mysqlnd driver, though -- best way would be to try ; but it'll still be PHP >= 5.3 only, anyway...

Another solution would be to have, on the PHP-side, some kind of a mapping-system (like an ORM) 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...

揽月 2024-08-31 11:30:55

如果使用 mysqli 而不是 PDO,请尝试此操作

$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);

try this if using mysqli instead of PDO

$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
不爱素颜 2024-08-31 11:30:55

我已经以手动方式实现了这一点。其实还不错,就几行而已。

按照建议,对查询结果的资源调用 mysqli_fetch_fields() 。

然后从 PHP 字段类型编号到 MySQL 数据类型的映射(请参阅此处的辛勤工作 http://www.php.net/manual/en/mysqli-result.fetch-field-direct.php)您可以从返回的各种数据库类型中转换您的值MySQLi 的字符串转换为 PHP 中的适当类型。

我不确定到底有多少放缓。

I've implemented this the manual way. It's actually not too bad, just a few lines.

As suggested, call mysqli_fetch_fields() on the resource resulting from your query.

Then from a mapping of the PHP field type numbers to MySQL data types (see industrious work here http://www.php.net/manual/en/mysqli-result.fetch-field-direct.php) you can convert your values from the wide range of database types returned as strings by MySQLi, into the appropriate type in PHP.

How much of a slowdown it is I'm not sure tho.

烙印 2024-08-31 11:30:55

除了 Pascal MARTIN 的回答之外,如果您使用 MySQLi 准备好的语句,您将使用本机类型获取数据。
试试这个:

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')");

$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

上面的示例将输出:

id = 1 (integer)
label = a (string)

您可以在此处获取更多信息:
https://dev。 mysql.com/doc/apis-php/en/apis-php-mysqli.quickstart.prepared-statements.html

In addition to Pascal MARTIN's answer, if you use MySQLi prepared statements you will get the data back using native types.
Try this:

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')");

$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>

The above example will output:

id = 1 (integer)
label = a (string)

You can get more info here:
https://dev.mysql.com/doc/apis-php/en/apis-php-mysqli.quickstart.prepared-statements.html

倚栏听风 2024-08-31 11:30:55

我写了一个函数来规避这个问题(对于 PDO):

/**
 * Converts columns from strings to types according to 
 * PDOStatement::columnMeta
 * 
 * @param PDOStatement $st
 * @param array $assoc returned by PDOStatement::fetch with PDO::FETCH_ASSOC
 * @return copy of $assoc with matching type fields
 */
function convertTypes(PDOStatement $statement, $assoc)
{
    for ($i = 0; $columnMeta = $statement->getColumnMeta($i); $i++)
    {
        $type = $columnMeta['native_type'];

        switch($type)
        {
            case 'DECIMAL':
            case 'TINY':
            case 'SHORT':
            case 'LONG':
            case 'LONGLONG':
            case 'INT24':
                $assoc[$columnMeta['name']] = (int) $assoc[$columnMeta['name']];
                break;
            case 'DATETIME':
            case 'DATE':
            case 'TIMESTAMP':
                $assoc[$columnMeta['name']] = strtotime($assoc[$columnMeta['name']]);
                break;
            // default: keep as string
        }
    }

    return $assoc;
}

当然,类型列表不完整并且转换过于简单,但对于启动很有用。

I wrote a function to circuvent this (for PDO):

/**
 * Converts columns from strings to types according to 
 * PDOStatement::columnMeta
 * 
 * @param PDOStatement $st
 * @param array $assoc returned by PDOStatement::fetch with PDO::FETCH_ASSOC
 * @return copy of $assoc with matching type fields
 */
function convertTypes(PDOStatement $statement, $assoc)
{
    for ($i = 0; $columnMeta = $statement->getColumnMeta($i); $i++)
    {
        $type = $columnMeta['native_type'];

        switch($type)
        {
            case 'DECIMAL':
            case 'TINY':
            case 'SHORT':
            case 'LONG':
            case 'LONGLONG':
            case 'INT24':
                $assoc[$columnMeta['name']] = (int) $assoc[$columnMeta['name']];
                break;
            case 'DATETIME':
            case 'DATE':
            case 'TIMESTAMP':
                $assoc[$columnMeta['name']] = strtotime($assoc[$columnMeta['name']]);
                break;
            // default: keep as string
        }
    }

    return $assoc;
}

Of course the type list are not complete and the conversion is oversimplified, but can be useful for start.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文