Skip to content
Advertisement

Dynamically generate type definition string for prepared statement

I’m working on a script that is essentially loading data from an API into a local MySQL database. The values are variable depending on what is returned by the API.

So far everything is working just fine up until I try to actually insert the rows into the MySQL db. Specifically, I know I should be using prepared statements, but I’m having trouble when I try to bind the variables to the prepared statement. When I try to run the below code, I get:

JavaScript

Here’s the code in question:

JavaScript

I freely admit that I’m a bit of a newbie at this, so I’m open to any and all suggestions on how to do this better. For what it’s worth, there’s never any direct user input, so I’m relatively unconcerned about security concerns if that makes a difference in how best to approach this.

Thanks in advance!

Advertisement

Answer

bind_param() actually takes variable arguments, not an array argument. But modern PHP has syntax for turning an array into multiple scalar arguments:

JavaScript

This is equivalent to passing the array elements as individual arguments:

JavaScript

But that’s awkward if you don’t know how many elements are in the array.


FYI, I like to use PDO instead of mysqli. You don’t have to bind anything, just pass the array of values as the argument to execute():

JavaScript

I find PDO to be a lot easier. The reason to use mysqli is if you have a lot of legacy code from the mid-2000’s that you need to adapt. If you’re just starting out, you have no old code. So you might as well adopt PDO to start with.

There’s a good tutorial for PDO: https://phpdelusions.net/pdo/

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement