«

Mar 02

Dynamic bind_param for mysqli update query in PHP

If you need to dynamically bind params to an UPDATE query when you are using mysqli statement you will face some troubles. But few lines far you are going to find the right solution for you

$query = '';
 $flag = false;
 $bindParam = '';
 $refArray = array();
 $refArray[] = &$bindParam; //set the 0 field
//Manage int value and first variable
 if (isset($our_integer_value)) {
 $query.='id_our_field = ?';
 $flag = TRUE;
 $bindParam.='i';
 $refArray[0] = &$bindParam;
 $refArray[] = &$our_integer_value;
 }
//Manage date
 if (isset($date)) {
 if ($flag)
 $query.=',';
 $query.='date = FROM_UNIXTIME(?)';
 $flag = TRUE;
 $bindParam.='s';
 $refArray[0] = &$bindParam;
 $refArray[] = &$date;
 }
//Manage string
 if (isset($date_info)) {
 if ($flag)
 $query.=',';
 $query.='date_info = ?';
 $flag = TRUE;
 $bindParam.='s';
 $refArray[0] = &$bindParam;
 $refArray[] = &$date_info;
 }
 
//ELEMENT ID
 $bindParam.='i';
 $refArray[0] = &$bindParam;
 $refArray[] = &$id_element;
$conne = $this->conn;//you could use you connection element
 $conne->set_charset('utf8');
 $stmt = mysqli_stmt_init($conne);
 $stmt->prepare("UPDATE element SET " . $query . " WHERE id_element = ? ");
 call_user_func_array(array($stmt, 'bind_param'), $refArray);
if ($stmt->execute()) {
 $stmt->close();
 return true;
 } else {
return $stmt->error;

 }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>