This accepted answer works and seems to be Google's most popular answer to this question. My problem is that I need to deploy the application in several environments, and I do not always have the ability to install the driver I need, plus I need decimal numbers to be numeric, not string. Therefore, I created a routine to enter the case register before the JSON encoding, which is easily modified to meet the requirements. It's like dropping a core from orbit.
First, use the Show Columns From command to get the columns from the table. MySQL query "SHOW COLUMNS FROM a table such as 'colmunname'": questions
$query = 'SHOW COLUMNS FROM ' . $table; //run with mysqli or PDO
Then put the types in an array indexed by the column name to make it easier to repeat. It is assumed that the result set from the columns of the show is in a variable named $ columns_from_table. http://php.net/manual/en/function.array-column.php
$column_types = array_column( $columns_from_table, 'Type', 'Field');
Then we want to remove the bracket from the type, which will be something like varchar (32) or decimal (14.6)
foreach( $column_types as $col=>$type ) { $len = strpos( $type, '(' ); if( $len !== false ) { $column_types[ $col ] = substr( $type, 0, $len ); } }
Now we have a linked array with the column name as index and formatted type as value, for example:
Array ( [id] => int [name] => varchar [balance] => decimal ... )
Now, when you make a choice from the table, you can iterate over the results and cast the value to the appropriate type:
foreach( $results as $index=>$row ) { foreach( $row as $col=>$value ) { switch( $column_types[$col] ) { case 'decimal': case 'numeric': case 'float': case 'double': $row[ $col ] = (float)$value; break; case 'integer': case 'int': case 'bigint': case 'mediumint': case 'tinyint': case 'smallint': $row[ $col ] = (int)$value; break; } } $results[ $index ] = $row; }
The switch statement can be easily modified to meet the requirements and can include date functions, etc. For example, in my case, the third party puts the currency values ββin the database as a decimal number, but when I get this data and I need to return it as JSON, I need it to be numbers, not strings.
Tested with PHP 7, 7.2 and JQuery 2, 3.