MySQL integer field is returned as string in PHP

前端 未结 15 2433
南旧
南旧 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:50

    You can do this with...

    1. mysql_fetch_field()
    2. mysqli_result::fetch_field_direct or
    3. PDOStatement::getColumnMeta()

    ...depending on the extension you want to use. The first is not recommended because the mysql extension is deprecated. The third is still experimental.

    The comments at these hyperlinks do a good job of explaining how to set your type from a plain old string to its original type in the database.

    Some frameworks also abstract this (CodeIgniter provides $this->db->field_data()).

    You could also do guesswork--like looping through your resulting rows and using is_numeric() on each. Something like:

    foreach($result as &$row){
     foreach($row as &$value){
      if(is_numeric($value)){
       $value = (int) $value;
      }       
     }       
    }
    

    This would turn anything that looks like a number into one...definitely not perfect.

提交回复
热议问题