Avatar of B O
B O
 asked on

How do I create a query and binding function that dynamically add values that are available before inserting to data base

I am trying to dynamically get values that are available

e.g. : I want to load 3 images while the database contains 5 columns for images
$data = [ 
title => ??,
user_id => ??,
body => ??,
img_0 => ??,
img_1 => ??,
img_2 => ??
];


This is my code:
public function addPost($data){


                $this->db->query('INSERT INTO posts (title, user_id, body, img_0, img_1, img_2, img_3, img_4) VALUES(:title, :user_id, :body, :img_0, :img_1, :img_2, :img_4)');
                
                //  Bind Values
                $this->db->bind(':title', $data['title']);
                $this->db->bind(':user_id', $data['user_id']);
                $this->db->bind(':body', $data['body']);


                // bind values of images
                $this->db->bind(':img_0', $data[0]['img_0']);
                $this->db->bind(':img_1', $data[1]['img_1']);
                $this->db->bind(':img_2', $data[2]['img_2']);
                $this->db->bind(':img_3', $data[3]['img_3']);
                $this->db->bind(':img_4', $data[4]['img_4']);
                


    
                // Execute
                if($this->db->execute()){
                    return true;
                } else {
                    return false;
                }
        }

Open in new window




PHP

Avatar of undefined
Last Comment
Ryan Chong

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Ryan Chong

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Your help has saved me hundreds of hours of internet surfing.
fblack61