So I have been asked a few times about binding parameters in MySQL or PDO objects in PHP, and I wanted to post a solution that many may find very handy.
For the first example, let’s say we have a “prepare” method set up to accept 2 parameters: 1) the SQL statement, and 2) an associative array whose key holds the name of the desired variable to bind, and the value holds that value of the variable. When the method is called and passed the parameters, you can only bind ONE param to the statement. To bind it, I use a trick that George Slater taught me called a “variable variable”. The method would look like:
<?php $sql = "SELECT column_name FROM table_name WHERE property_name = ?"; $parameters = array( "property_name" => $_POST["inputValue"], "action" => $_POST["submittedAction"] ); $DBobj = new DBOb(); if($parameter["action"] == "whatever_actionYou_want") { unset($parameters["action"]); $DBobj->prep($sql, $parameters); } // continue statements..... ?> <?php /* * instructional db class */ class DBobj { // code code code public function prep($stmt, array $params) { if($stmt == null || empty($stmt)) return null; $newStatementObj = $this->DataBaseConnectionReferenceLink->prepare($stmt); foreach($params as $variableName => $value) { // the variable variable $$variableName = $value; $type = gettype($value)[0]; } $newStatementObj->bind_param($type, $$variableName); $newStatemnetObj->execute(); // .... continue code here and dont forget to close() the statement exec. // also keep in mind that if you need to bind more than one set in the parameter array, you // need to use: call_user_func_array(array($statement, "bind_param"), $varsToBindArray) ?>
Leave a Reply
You must be logged in to post a comment.