I am writing a function that takes a mysqli_result and adds all of the returned columns into an associative array in my result object. As of right now everything that is returned via the mysqli::multi_query is in string format, while the description as to what value type the value should be is kept in the array of objects returned by mysqli::fetch_fields. I feel that so far this is pretty confusing so let me code it out
if ($mysqli->multi_query($inputQuery)) {
if ($result = $mysqli->store_result()) {
//$fields is an array of custom objects
$fields = $result->fetch_fields();
//$fieldType is an integer that is the value of a mysqli predefined constant
$fieldType = $fields[0]->type;
if ($curRow = $result->fetch_row()) {
//No matter what the value type in the database of this item is, and no
//matter what $fieldType corresponds to, $curVal is going to be a string
$curVal = $curRow[0];
}
}
}
The integer that $fieldType takes is, from my understanding, the VALUE of a predefined mysqli constant which can be found here: http://www.php.net/manual/en/mysqli.constants.php
I know a similar question to this has been posted here: PHP mysqli_fetch_field data type but I am more interested in mapping the values back to their respective keys.
What I would like to do is cast the string value of $curVal into the correct value type based on the mapping of $fieldType to the mysqli predefined constant. I suppose that I could brute force check against every predefined constant, or I could create an associative array with value -> key instead of key -> value and then reference that, but I feel like there should be an easier way to go about this.
My question, then, is what is the easiest way to find a predefined constant in PHP by its value? Do I access these mysqli predefined constants the same way that I access global constants in PHP or do I have to do something like $mysqli->PREDEFINED_CONSTANT?
Best regards,
解决方案
The constants are not part of the object so using $mysqli::CONSTSANT or $mysqli->CONSTANT won't work that way.
Here's the beginning of an example. You'll have to look at the rest of the MySQLi constants and finish the switch statement. The ones that aren't included will remain strings.
$result = $mysqli->query('SELECT * FROM `accounts`');
$fields = $result->fetch_fields();
// Loop through each row.
while ( $row = $result->fetch_row() )
{
// Loop through each field.
foreach ( $row as $key => &$value )
{
// Using the $key, find the type of the current field.
switch ( $fields[$key]->type )
{
// Convert INT to an integer.
case MYSQLI_TYPE_TINY:
case MYSQLI_TYPE_SHORT:
case MYSQLI_TYPE_LONG:
case MYSQLI_TYPE_LONGLONG:
case MYSQLI_TYPE_INT24:
$value = intval($value);
break;
// Convert FLOAT to a float.
case MYSQLI_TYPE_FLOAT:
case MYSQLI_TYPE_DOUBLE:
$value = floatval($value);
break;
// Convert TIMESTAMP to a DateTime object.
case MYSQLI_TYPE_TIMESTAMP:
case MYSQLI_TYPE_DATE:
case MYSQLI_TYPE_DATETIME:
$value = new DateTime($value);
break;
}
}
var_dump($row);
}