Why does $wpdb return strings for mysql integer values?

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

Read More
$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.

Related posts

3 comments

  1. 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 .

    $int_id = absint( $wp_posts[0]->ID );
    

    Also, not sure if your DB call is just simply an example, but I suggest using get_posts, or better yet, a WP_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 use wp_reset_query after using the above to methods to ensure you are reverting back to the main loop.

  2. 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.

  3. If you are running Ubuntu:

    sudo apt-get remove php5-mysql
    sudo apt-get install php5-mysqlnd
    sudo service apache2 restart
    

Comments are closed.