Mysqli and BLOB binary database fields
This post exists to save you hours of research on the web. The following things may be true about you:
- You recently transitioned from mysql PHP functions to mysqli functions (staying current)
- You prefer procedural PHP over object-oriented PHP (functions and arrays are cooler than classes)
- You are storing some data in a MySQL BLOB, MEDIUMBLOB, or LONGBLOB field, which is Binary
Now, the only advice I found involved storing a file that is already binary. Fine for them, but what if the binary data is PHP created?
I use the following functions to store Arrays in MySQL BLOB fields by converting them to JSON, then using gzcompress to shrink the data down as well as speed up the transfer time and reduce disk I/O. NOTE: The gzcompress() function returns binary data.
I’m not going to get into the discussion of when this may or may not be appropriate for you to use, but I will discuss the problem you run into when doing this in mysqli compared to mysql.
Simply put, you can’t just send binary data normally. It requires a prepared statement. Since I prefer procedural code, I’ve put together a simple example below that creates an empty array.
While I recommend reading the documentation on mysqli_stmt_bind_param() function, the basics is that you are passing over the prepared statement object ($stmt), then declaring the type of value it should expect (b = binary), and then giving it that value (we’re using $null temporarily).
The following line mysqli_stmt_send_long_data() is what actually switches it to your binary data and makes it all work. The second passed value (0 in the above example) represents the position (order of the ? like a numerically indexed array) in the prepared statement. Below you’ll find an example where this will be clearer.
Let’s look at a more complicated function that uses two prepared variables.