I find it very inconvenient and hard to understand that the default behavior of the WordPress db-interface is to convert all integer (and float?) types to strings.
e.g
$wp_posts = $wpdb->get_results('SELECT * from wp_posts');
$unexpected_type = gettype($wp_posts[0]->ID) == 'string';
Please confirm my suspicion that this is done in order to support very large (capacious) integer types that are not supported by PHP, or provide an alternative explanation as to why one would chose to convert integers to strings.
The second part of my question, as maybe expected, is to find out if there is a built in configuration parameter to the wpdb
class that would allow one to request integers for integer-type records.
As the other people have mentioned in the comments, due to the libraries that source uses, strings are returned. If you need to convert to an integer for a comparison or function call, just use WordPress’s
absint
function .Also, not sure if your DB call is just simply an example, but I suggest using
get_posts
, or better yet, aWP_Query
if possible. This allows you to maintain all of the sanitization those functions have built into them, keeping the security of your site pretty solid. Also remember to usewp_reset_query
after using the above to methods to ensure you are reverting back to the main loop.Because the MySQL interface library used prior to PHP 5.3 returns everything as strings. The new (optional) interface, MySQL Native Driver, can return integer types if enabled at compile time.
For details, look into libmysql and mysqlnd.
If you are running Ubuntu: