开发者

mysql_query preserve the data type created in the table on return?

开发者 https://www.devze.com 2022-12-21 03:30 出处:网络
I have a table in mysql: CREATE TABLE user (id INT, name VARCHAR(250)); I query the table: $result = mysql_query(\"SELECT id,name FROM user\");

I have a table in mysql:

CREATE TABLE user (id INT, name VARCHAR(250));

I query the table:

$result = mysql_query("SELECT id,name FROM user");

I gather the results:

while($row = mysql_fetch_assoc($result) $rv[] = $row;

And I return the data:

echo 开发者_C百科json_encode($rv);

The problem is that the id returns as string and not int, even before the json_encode. If i force $row['id'] = (int)$row['id']; - it works fine.

How can i force mysql to return the correct data type in the $row?

10x.


Unfortunatly, with PHP <= 5.2, the MySQL functions/classes (i.e. mysql_*, mysqli_*, and PDO) are based on libmysql -- a C library which provides support for communication with the MySQL server.

Functions using that library always return strings, even for integer and float columns -- and there is nothing you can do about that : the only solution is to have some "mapping layer" (like an ORM) that "knows", on the PHP side, which type each column should be, and will do the conversion each time some data is fetched from the database.

Note : the way you're inserting data doesn't change anything about the fact that you'll get strings when fetching data from the DB.


With PHP >= 5.3, functions that communicate with a MySQL server can use mysqlnd (MySQL Native Driver) instead of libmysql -- this has to be configured at compile-time, though.

And being able to communicate with "native" data-types, under certain circumstances, is one of the nice things that mysqlnd provides ; about that, there should be a couple of interesting informations is this article : PHP: New network traffic, CPU and memory savings with mysqlnd.


To makes things short :

  • With PHP 5.2, you'll only get strings from the database ; and you'll have to do some type-conversion yourself
  • With PHP 5.3, you might get native datatypes -- at least in some cases.


PDO->bindColumn can this

$stmt = $dbh->prepare($sql);

$stmt->bindColumn('int_col', $intVar, PDO::PARAM_INT);
$stmt->bindColumn('string_col', $strVar, PDO::PARAM_STR);

$stmt->execute();

$stmt->fetch(PDO::FETCH_BOUND);

$intVar will be automatically converted to int

0

精彩评论

暂无评论...
验证码 换一张
取 消