Advertisement
Guest User

Untitled

a guest
Feb 24th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. <?php
  2. class MY_Model extends CI_Model {
  3.  
  4. /*
  5.  
  6. ... you might have some logic of your own ...
  7.  
  8. */
  9.  
  10. /**
  11. * Runs a query and returns an array of array, with correct types (as Code Igniter
  12. * returns everything as string)
  13. * @param string $sql
  14. * @return array Array of array, where the first index is the row number, second is column name
  15. * @author pamaral
  16. */
  17. public function queryWithProperTypes($sql) {
  18.  
  19. $query = $this->db->query($sql);
  20. $fields = $query->field_data();
  21. $result = $query->result_array();
  22.  
  23. foreach ($result as $r => $row) {
  24. $c = 0;
  25. foreach ($row as $header => $value) {
  26.  
  27. // fix variables types according to what is expected from
  28. // the database, as CodeIgniter get all as string.
  29.  
  30. // $c = column index (starting from 0)
  31. // $r = row index (starting from 0)
  32. // $header = column name
  33. // $result[$r][$header] = that's the value to fix. Must reference like this because settype uses a pointer as param
  34.  
  35. $field = $fields[$c];
  36.  
  37. switch ($field->type) {
  38.  
  39. case MYSQLI_TYPE_LONGLONG: // 8 = bigint
  40. case MYSQLI_TYPE_LONG: // 3 = int
  41. case MYSQLI_TYPE_TINY: // 1 = tinyint
  42. case MYSQLI_TYPE_SHORT: // 2 = smallint
  43. case MYSQLI_TYPE_INT24: // 9 = mediumint
  44. case MYSQLI_TYPE_YEAR: // 13 = year
  45. settype($result[$r][$header], 'integer');
  46. break;
  47.  
  48. case MYSQLI_TYPE_DECIMAL: // 0 = decimal
  49. case MYSQLI_TYPE_NEWDECIMAL: // 246 = decimal
  50. case MYSQLI_TYPE_FLOAT: // 4 = float
  51. case MYSQLI_TYPE_DOUBLE: // 5 = double
  52. settype($result[$r][$header], 'float');
  53. break;
  54.  
  55. case MYSQLI_TYPE_BIT: // 16 = bit
  56. settype($result[$r][$header], 'boolean');
  57. break;
  58.  
  59. }
  60.  
  61. $c = $c + 1;
  62. }
  63. }
  64.  
  65. return $result;
  66. }
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement