简体   繁体   English

使用 mysqli bind_param 动态绑定参数

[英]Binding parameters dynamically with mysqli bind_param

so I've been looking up a solution to bind parameters dynamically with php and here is a function that I made.所以我一直在寻找一种使用 php 动态绑定参数的解决方案,这是我制作的一个函数。

 public function getEntity($tableName, $fieldList, $keyValueArray = NULL) { // First construct the sql to be used to get the entity if(is_array($fieldList)) { $sql = "SELECT "; foreach($fieldList as $field) { $sql .= $field." , "; } $sql = rtrim($sql, ' , '); } else { $sql = "SELECT ".$fieldList; } $sql .= " FROM ".$tableName; if($keyValueArray != NULL) { $sql .= " WHERE "; foreach($keyValueArray as $key => $value) { $sql .= $key." = ? AND "; } $sql = rtrim($sql, ' AND '); } //Then grab the connection $connection = $this->getConnection(); //Prepare the statement $stmt = $connection->prepare($sql); if($stmt === false) { trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $connection->errno . ' ' . $connection->error, E_USER_ERROR); } // Bind the paramaters if($keyValueArray != NULL AND count($keyValueArray) < 2) { $stmt->bind_param("s", $keyValueArray[key($keyValueArray)]); } elseif($keyValueArray != NULL) { $valueArray = array(); $string = NULL; for($i = 0; $i < count($keyValueArray); $i++) { $string .= "s"; // for temp solution } $valueArray[] = &$string; foreach($keyValueArray as $key => $value) { $valueArray[] = &$keyValueArray[$key]; } call_user_func(array($stmt, 'bind_param'), $valueArray); } //Execute the statement $stmt->execute(); //Grab the results and stuff into multidimensional array $data = $stmt->result_metadata(); $fields = array(); $currentrow = array(); $results = array(); //Store references to keys in $currentrow while ($field = mysqli_fetch_field($data)) { $fields[] = &$currentrow[$field->name]; } // Bind statement to $currentrow using the array of references call_user_func_array(array($stmt, 'bind_result'), $fields); // Iteratively refresh $currentrow array using "fetch", store values from each row in $results array $i = 0; while ($stmt->fetch()) { $results[$i] = array(); foreach($currentrow as $key => $val) { $results[$i][$key] = $val; } $i++; } $connection->close(); return $results; }

I then run this function something like this:然后我像这样运行这个函数:

 $keyValueArray['firstName'] = 'John'; $keyValueArray['lastName'] = 'Doe'; $fieldListArray[] = 'firstName'; $fieldListArray[] = 'lastName'; print_r($db->getEntity('ACCOUNT', $fieldListArray, $keyValueArray));

However, when I run the function.但是,当我运行该功能时。 I get an error that says我收到一个错误提示

Wrong parameter count for mysqli_stmt::bind_param()

I'm not sure what I'm doing wrong.我不确定我做错了什么。 Any help would be appreciated.任何帮助,将不胜感激。

调用bind_param时,您需要使用call_user_func_array ,而不是call_user_func

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM