mysqli_fetch_assoc (& PDO fetch assoc) storing num

2020-04-21 07:21发布

问题:

as usual, did my duty to look everywhere for the sol but to no avail.

mysqli_fetch_assoc is (apparently) storing my numbers as strings.

Normally, I could care less, but my site is nearly 100% ajax, and it moves around a lot of data, so all of those json "'s start to add up.

If I'm just grabbing one column value, I can intval, but I want to grab whole rows with associated column names.

Is there a way to get mysqli_fetch_assoc (and PHP PDO's fetch assoc) to store numbers as numbers?

Many thanks in advance!

回答1:

MySQL can store 64-bit numbers and unsigned numbers, neither of which are supported by default in PHP's int type. If you try to fetch numeric data from the database that overflows the int variables in PHP, you'll lose information. That's why PHP database clients fetch numbers as strings.

Re your comment:

Yes, if you're concerned about the size of JSON, convert the data in your PHP app for more compact representation.

Though since you said you're transferring column names as part of your JSON, it seems like the difference between string-formatted ints and binary ints is not your bottleneck anyway.

I mean, converting a string-int to a binary int reduces the bits by about 50%. But if you have column names as strings anyway, you're only shrinking a small portion of the JSON. The columns are still strings.