Sunday, February 18, 2018

php - How do I process an associative array properly in a PDO (or MySQLi) query?

I'm using MySQLi for a project (but could easily switch to PDO, read the edit at the bottom). What I want is to be able to process an associative array into an mysql query without typing every key/value pair manually. I know that might be simply put, but I'm still in a learning process when it comes to MySQLi/PDO. To make it clear what I mean here is an example:



Let's say I have this associative array:




$data = array(
'name' => 'Objective',
'short_name' => 'OB',
'generation' => 1
);


What I want is to create a query like this:




UPDATE signals SET ? = ? WHERE sid = '1'


And it to become a query like this (or instead of an UPDATE, an INSERT, SELECT etc.):



UPDATE signals SET
name = 'Objective',
short_name = 'OB',
generation = 1
WHERE sid = '1'



So basically my question is: is this possible with MySQLi or PDO itself? If it's possible how would I have to do this?
I've read on preparing statements before executing, but it's not getting to me yet. Hopefully someone can help me out.



Edit: I'm still very early into the project so i'm also fine with using PDO, but the same question remains. I did look into both PDO and mysqli, and I'm not sure how to do it with PDO either. So for the sake of the question i'll add PDO to as a tag and to the question.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...