3

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.

3

As the other gentlemen 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.

  • 1
    Wordpress posts have nothing to do with the question, but thank you for the informative answer. – Ярослав Рахматуллин Jan 13 '14 at 13:02
  • 1
    Yes, I figured it was just example code, but just thought I'd toss it in anyways :) – Eric Holmes Jan 13 '14 at 14:42
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.

0

If you are running Ubuntu:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.