Created
February 24, 2017 16:55
-
-
Save paulera/370fb995988d983909e4a19769ee2f5d to your computer and use it in GitHub Desktop.
Code Igniter db engine return datasets with all values as strings. This function allows a controller to run a query and return an array of arrays with the correct object types. One might want to tweak it to support bindings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MY_Model extends CI_Model { | |
/* | |
... you might have some logic of your own ... | |
*/ | |
/** | |
* Runs a query and returns an array of array, with correct types (as Code Igniter | |
* returns everything as string) | |
* @param string $sql | |
* @return array Array of array, where the first index is the row number, second is column name | |
* @author pamaral | |
*/ | |
public function queryWithProperTypes($sql) { | |
$query = $this->db->query($sql); | |
$fields = $query->field_data(); | |
$result = $query->result_array(); | |
foreach ($result as $r => $row) { | |
$c = 0; | |
foreach ($row as $header => $value) { | |
// fix variables types according to what is expected from | |
// the database, as CodeIgniter get all as string. | |
// $c = column index (starting from 0) | |
// $r = row index (starting from 0) | |
// $header = column name | |
// $result[$r][$header] = that's the value to fix. Must reference like this because settype uses a pointer as param | |
$field = $fields[$c]; | |
switch ($field->type) { | |
case MYSQLI_TYPE_LONGLONG: // 8 = bigint | |
case MYSQLI_TYPE_LONG: // 3 = int | |
case MYSQLI_TYPE_TINY: // 1 = tinyint | |
case MYSQLI_TYPE_SHORT: // 2 = smallint | |
case MYSQLI_TYPE_INT24: // 9 = mediumint | |
case MYSQLI_TYPE_YEAR: // 13 = year | |
settype($result[$r][$header], 'integer'); | |
break; | |
case MYSQLI_TYPE_DECIMAL: // 0 = decimal | |
case MYSQLI_TYPE_NEWDECIMAL: // 246 = decimal | |
case MYSQLI_TYPE_FLOAT: // 4 = float | |
case MYSQLI_TYPE_DOUBLE: // 5 = double | |
settype($result[$r][$header], 'float'); | |
break; | |
case MYSQLI_TYPE_BIT: // 16 = bit | |
settype($result[$r][$header], 'boolean'); | |
break; | |
} | |
$c = $c + 1; | |
} | |
} | |
return $result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment