mysql_query returns only string type for int/fload db type

匿名 (未验证) 提交于 2019-12-03 02:21:02

问题:

I am trying to process a MySQL select result. My problem is that the sample code below only returns an Array containing all values as string-type even for columns that contain integers and floats.

$sth = mysql_query($selectstr); $rows = array(); while($r = mysql_fetch_row($sth)) {   foreach ($r as $value) echo gettype($value), "\n"; } 

If I pass that array in $r to json_encode(..) I get JavaScript string values in the output (surrounded by quotes) and not unquoted number values (what i need).

How can I query the MySQL database and get a row-array containing the values with the correct type?

Update: Second parameter of mysql_fetch_row(..) removed. Originally I used mysql_fetch_array(..) which accepts the second parameter.

回答1:

None of the mysql_fetch_* functions are supposed to cast values according to their columns' types. For some, PHP doesn't even provide a matching internal data representation (think: BIGINT).

If you know the data-type of a query's result, you'll need to cast them manually. Otherwise mysql_field_type() would give you a hint on what type to convert the results to.



回答2:

I suggest folow code:

<?php $sth = mysql_query($selectstr); $rows = array(); while($r = mysql_fetch_row($sth,MYSQL_NUM)) {   foreach ($r as $key => $value)    {      if (is_numeric($value)) {        $r[$key] = (float)$value;      }   } } ?> 


回答3:

In the end I changed my code as follows:

$sth = mysql_query($selectstr); $rows = array(); while($r = mysql_fetch_row($sth)) {   for ($i = 0; $i < count($r) ; $i++)      settype($r[$i],float);  } 

It assumes that all selected columns in the result set contain numeric values.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!