Search code examples
phpmysqlcodeignitercodeigniter-2

query result array, each row's column field to string


I'm using CodeIgniter and I wrote the following code in one of my model (.php file) to do preg_split operation on one column value for each rows matching the query.

For context, I have no idea how to do debugging such backend operation and am lost / afraid of blowing up the database. The problem is I don't know if I'm doing the preg_split operation on a string or an array value.

The field type for fruits column is varchar(32) which is a string, but would calling $row['fruits'] really return a pure string?

$query = $this->db->query($sql);
foreach ($query->result_array() as $row) {
    //  theoretically $s = 'apple banana'
    $s = $row['fruits'];
    //  theoretically parts[0]=apple, parts[1]=banana
    $parts = preg_split('/\s+/', $s); 
}

Solution

  • In PHP database return values are strings (variants), so $row["fruits"] would return a string even if the MySQL datatype was an integer you would still get a valid string. Because PHP is not strongly typed, it does a lot of automatic casting for you meaning you can use results as integers or floats or strings (and interchangeably) in your code.

    One final point of note: PHP will return (MySQL)NULL values as an empty string "".

    Hope this helps!