September 25, 2008

241 words 2 mins read

mysqli & Custom Session Handlers in PHP 5

I’ve never been one to use mysqli in PHP, I’ve never needed to. Recently though, I’ve started using stored procedures, which necessitated the move to mysqli. Now, this really isn’t that big of a deal. After all, a search and replace of mysql_ with mysqli_ and adding the connection flag, and you are good. Here’s where it got fun for me though. I was using Custom Session Handlers (so I could write to the DB, instead of to a file — like many people do). Everything worked peachy, except for my “Write” override. For some god damned reason the thing kept kicking out _Warning: mysqli_query() expects parameter 1 to be mysqli, null given_.

I spent 3+ hours trying to debug this problem. I thought there was something in my code stomping the connection variable, or otherwise munging it (I was reusing old code). I put in DB “Ping” checks EVERYWHERE. They all worked, except for that subroutine. Well, after the aforementioned frustrating hours, I seriously got into the googling because someone had to have some insight into it. I found some bug reports and other comments that eventually steered me to a forum post.

Short answer? Add session_write_close(); to the end of the script. For what ever reason the session shutdown is “Broken” and tries to shutdown after the database is disconnected. So shut it down early and you are good. Yea. One simple call and it fixed my problems. ::Grumbles::