MySQL integer field is returned as string in PHP

前端 未结 15 2368
南旧
南旧 2020-11-22 16:17

I have a table field in a MySQL database:

userid INT(11)

So I am calling it to my page with this query:

\"SELECT userid FR         


        
15条回答
  •  误落风尘
    2020-11-22 16:58

    I like mastermind's technique, but the coding can be simpler:

    function cast_query_results($result): array
    {
        if ($result === false)
          return null;
    
        $data = array();
        $fields = $result->fetch_fields();
        while ($row = $result->fetch_assoc()) {
          foreach ($fields as $field) {
            $fieldName = $field->name;
            $fieldValue = $row[$fieldName];
            if (!is_null($fieldValue))
                switch ($field->type) {
                  case 3:
                    $row[$fieldName] = (int)$fieldValue;
                    break;
                  case 4:
                    $row[$fieldName] = (float)$fieldValue;
                    break;
                  // Add other type conversions as desired.
                  // Strings are already strings, so don't need to be touched.
                }
          }
          array_push($data, $row);
        }
    
        return $data;
    }
    

    I also added checking for query returning false rather than a result-set.
    And checking for a row with a field that has a null value.
    And if the desired type is a string, I don't waste any time on it - its already a string.


    I don't bother using this in most php code; I just rely on php's automatic type conversion. But if querying a lot of data, to then perform arithmetic computations, it is sensible to cast to the optimal types up front.

提交回复
热议问题