简体   繁体   中英

Detect data type while using fetch_array with 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);
}

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

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)?

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

Thanks a lot for your help

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 .

Try this

$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);

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

Query the information_schema.columns table as follows:

SELECT DATA_TYPE FROM information_schema.COLUMNS WHERE TABLE_NAME = 'tbl1' AND COLUMN_NAME = 'keycol'

Assuming your table is tbl1 and the column in question is keycol. However, it does strike me that json_encode will probably make your life easier and probably infinitely so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM