Skip to content
Advertisement

Dynamic MySQL Query with PHP

I am looking for a way to make dynamic queries to my MySQL server. At the moment this is the code I use to update data on the server:

JavaScript

As you can see, the SQL column names are the same as thedeskAttrkeys. I’m looking for a way to make this line a loop so, that I don’t need to change this line if I were to add more columns to the MySQL table.

It would look something like this:

JavaScript

How would I write the code above so it will actually work?


**EDIT**

Maybe it will be helpful to know that$deskAttr is an array of objects, and the name of the columns are the same as the name of the objects keys.

Here is what I mean in pseudo code:

JavaScript

Obviously this would add an extra comma at the end of the query before the WHERE part, but hopefully you get what I’m trying to achieve.

Advertisement

Answer

You can do it with slight change in your code by using PHP’s implode() function.

Take a blank array, concatenate the update parameters to it.

And then if is not empty(), implode() to get string.

Updated Code:

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