所以我一直在寻找一个用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; }
然后我运行这样的函数:
$keyValueArray['firstName'] = 'John'; $keyValueArray['lastName'] = 'Doe'; $fieldListArray[] = 'firstName'; $fieldListArray[] = 'lastName'; print_r($db->getEntity('ACCOUNT', $fieldListArray, $keyValueArray));
但是,当我运行该功能时。我收到一条错误
Wrong parameter count for mysqli_stmt::bind_param()
我不确定我做错了什么。任何帮助将不胜感激。
答案 0 :(得分:1)
调用call_user_func_array
时,您需要使用call_user_func
,而不是bind_param
。