I have some code in a drupal 7 site that makes repeated requests to an external database using mysqli. To speed up the code, I was hoping that I could store the mysqli-connection object in the cache, like this:

// Check if DB-connection already loaded
$external_db = &drupal_static(__FUNCTION__);

if ( !isset($external_db) ){
    // Check if DB-connection in cache
    if( $cached_db = cache_get('external_db', 'cache') ) { 
           $external_db = $cached_db->data;

    // Else make a new connection
    else { 
        $external_db = mysqli_connect('someip', 'someuser', 'somepass', 'somedb');
        cache_set('external_db', $external_db, 'cache');

However, something spooky happens to the connection object when I fetch it from out of the cache: it seems to have lost most of its properties. For example, the properties client_info and host_infoare being unset.

Any idea what causes this? Does Drupal delete those properties, or is it something built in to mysqli? Are there alternatives to mysqli that are cacheable?

Thanks a lot you guys!


To speed up the code, I was hoping that I could store the mysqli-connection object in the cache

It doesn't work like that. For one thing a database connection cannot be serialised (not in any meaningful way at least, as you've discovered). Once the page request is done with, the connection is closed. You can't force it to stay open by maintaining a reference to it, as that physically won't work when you come to accessing the network.

Separately, you should never have any cause to use mysql_connect() in Drupal (or ever if you want to be technical - it was deprecated a long time ago). Drupal's database connection is as optimised as you'll need such a thing to be, so you should just use that.

  • Answered within 10 minutes after posting - amazing :) I didn't know a database connection has an actual physical meaning in the network. I'll go and look that up! Thanks a lot! As for Drupal's own DBTNG: I would like to use it, but that would mean rewriting all the queries of the code that I inherited - a few hundreds... ugh. I'm currently playing around with the query_coder module - if I find a way to use it within a module, I'll post it somewhere! Mar 17 '15 at 14:34
  • No worries ;) This is the best resource I can find to explain it in PHP specifically: stackoverflow.com/questions/1341494/…
    – Clive
    Mar 17 '15 at 14:36
  • Fa-bu-lous! Cheers! Mar 17 '15 at 14:37

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.