1

Im working with a lot of sql queries. While I have not mastered PDO yet I was hoping to come here for a bit of help since my previous searches didn't deliver much in terms of help. I did come across this link on SO but it seems a bit out of scope to what I am doing

Consider The following code, which works 100%;

public function composeMsg($userID, $toUser, $subject, $msg, $sentOn ){
        $db = DB::getInstance();
        $sql = "INSERT INTO messages (userID, fromID, subject, body, senton) values (:userID, :toUser, :subject, :msg, :sentOn )";
        $stmnt = $db->prepare($sql);
        //NOT EFFICIENT
        $stmnt->bindValue(':userID', $userID);
        $stmnt->bindValue(':toUser', $toUser);
        $stmnt->bindValue(':subject', $subject);
        $stmnt->bindValue(':msg', $msg);
        $stmnt->bindValue(':sentOn', $sentOn);

        $stmnt->execute();
        if($stmnt->rowCount() > 0){
            return true;
        }
        else{
            return false;
        }
    }//FUNCTION

Im finding myself to continuously type $stmnt->bindValue(':value', $value) multiple times as can be seen from the code above. Im looking for a build in PDO function or something similar which I can make use of to avoid all the repetition.

Any advise welcomed

Timothy Coetzee
  • 5,626
  • 9
  • 34
  • 97
  • Thanks Nigel I just had a peek will inspect it more. The frustrating thing for beginners like myself is that the PHP Manual can often be over complicated and hard to grasp, with many examples being overkill – Timothy Coetzee Jul 23 '17 at 07:31

1 Answers1

2

Binding them all as part of the execute...

   $stmnt->execute([':userID'=> $userID,
         ':toUser'=> $toUser,
         ':subject' => $subject,
         ':msg' => $msg,
         ':sentOn' => $sentOn]);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55