在MySQLi中使用fetch_array时检测数据类型 [英] Detect data type while using fetch_array with MySQLi

查看:129
本文介绍了在MySQLi中使用fetch_array时检测数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时使用MySQLI以这样的方式获取数组

while fetching an array with MySQLI in a way such that

$sql = <<<SQL
    SELECT *
    FROM `users`
    WHERE `live` = 1 
SQL;

if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}

while($row = $result->fetch_assoc()){
    echo var_dump($row);
}

我获得所有值均为string类型的关联数组.

I obtain associative arrays where all the values are of type string.

哪种方法最适合检测列类型(VARCHAR,DATETIME,INT,FLOAT)并用正确的类型(字符串,整数,空值)填充关联数组(或创建唯一的关联数组)?

Which is the most elegant way to detect the column type (VARCHAR, DATETIME, INT, FLOAT) and fill the associative arrays (or create an unique associative array) with the right typing (string, integer, null)?

这对于返回结果json_encode d进行进一步的客户端处理非常有用.

This would be very useful while returning the results json_encoded for further client-side processing.

非常感谢您的帮助

推荐答案

首先,您问的是错误的问题.
您实际上不需要列类型.实际上,您已经可以从具有简单PHP条件的数字中分辨出一个字符串.但是这两种方法都不会告诉您 NULL .

First of all, you are asking wrong question.
You don't actually need a column type. As a matter of fact, you can tell a string from a number with simple PHP condition already. But neither method will tell you NULL.

尝试一下

$sql = "SELECT * FROM users WHERE live = 1";
$stm = $db->prepare($sql) or trigger_error($db->error);
$stm->execute() or trigger_error($db->error);
$res = $stm->get_result();
$row = mysqli_fetch_assoc($res);

如果幸运的话,您将设置所有类型.
如果不是,则需要在PHP中启用mysqlnd

If you get lucky, you'd get all types set.
If not - you will need to enable mysqlnd in PHP

这篇关于在MySQLi中使用fetch_array时检测数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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