Skip to content
Advertisement

Create a wordpress update query with an associative array done by a for or foreach loop

I want to create an associative array by a loop to add it in a update. The problem i have is that i dont know how to go through each element of the 2 arrays for creating an associative array to put in the update query.

You can see down here i put the array inside another array in the update query but its wrong.

I have the following as an example:

JavaScript

The array is associative as i said. The update function should look like that:

JavaScript

But i would like to do that way:

JavaScript

Advertisement

Answer

You can create an associative array from your $names and $data like this:

JavaScript

That will create an array like this:

JavaScript

You can see the output here (using dummy data of course): https://sandbox.onlinephpfunctions.com/code/68c5f0a92b33625c437e4c5b9ef17c6f9b2ec4bb

Alternatively, as you are using the $_POST, you could create your array this:

JavaScript

The whole code would then be:

JavaScript

IMPORTANT NOTE:

You are using table and update in your code, so if you are adding this into a database, you should sanitize any user-provided data before adding it to you DB, otherwise you are wide open to SQL injection.

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