我正在尝试创建一个动态函数来执行mysqli查询。
以下是常规查询的示例:
public function myfunc() {
$name = "ryan";
$stmt = $this->db->prepare("SELECT name, age, id FROM users WHERE name = ?");
$stmt->bind_param( "s", $name );
$stmt->execute();
$stmt->bind_result( $name2, $age, $id );
while( $stmt->fetch() )
$users[] = array( 'name' => $name2, 'age' => $age, 'id' => $id );
$stmt->close();
return $users;
}
我正在努力做一些事情:
public function query( $myquery, $params, $types, $returns ) {
$stmt = $this->db->prepare( $myquery );
$stmt->bind_param( $types, $params );
$stmt->execute();
$stmt->bind_result( $returns_array );
$i = 0;
while( $stmt->fetch() ) {
$users[] = array( $returns[$i] => $returns_array[$i++], .... );
}
$stmt->close();
return $users;
}
我可以在一个简单易用的函数中动态使用预准备语句。
调用它的示例:
$users = query( "SELECT name, age, id FROM users WHERE name = ?", array('ryan'), "s", array('name','age','id'));
然后您可以通过以下方式轻松调用数据:
$users[0]['name']..
$users[0]['age']..
$users[0]['id']..
我对如何实现这一点感到有点困惑,但你们有什么想法或地方我可以开始吗?代码特别有用。
我还发现了这篇文章:http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli
但我不希望它对操作系统上安装的软件过于具体。
更新#2 我需要返回密钥 - >多个数组的数组的值。我想出了这个,但似乎无法实现它。我得到了id的值,而不是我要求的东西。
public function query( $query_string, $params = null, $param_types = null) {
//prepare the statement
$stmt = $this->db->prepare($query_string);
//check if the sql query is wrong.
if($stmt === false) {
echo "Wrong SQL: " . $query_string . "<br />Error: " . $this->db->errno . " " . $this->db->error;
}
if($params != null && $param_types != null) {
//build the array that needs to pass the args to bind_param.
$a_params = array();
$a_params[] = &$param_types;
for($i=0; $i<count($params); $i++)
$a_params[] = &$params[$i];
// $stmt->bind_param('s', $param); equivalent
call_user_func_array(array($stmt, 'bind_param'), $a_params);
}
//run the query
$stmt->execute();
//gather column names
$metadata = $stmt->result_metadata();
$field_names = array();
$fields = array();
$results = array();
$i = 0;
// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while( $field = $metadata->fetch_field() ) {
//for binding the results
$var = $field->name;
$null_v = null;
$fields[$var] = &$null_v;
//for storing the field names
$field_names[$i] = $var;
$i++;
}
// Bind Results
call_user_func_array(array($stmt,'bind_result'),$fields);
//put results into an array
$i = 0;
while ($stmt->fetch()) {
for( $k = 0; $k < count($fields); $k++){
$results[$i][$field_names[$k]] = $fields[$field_names[$k]];
}
$i++;
}
$stmt->close();
return $results;
}
我是如何调用和检索数据的。
$users = $TCS->query("SELECT name, age, id FROM test");
foreach($users as $user) {
echo $user['name'];
}
但它正在输出他们的ID。 (1,2,3)应该输出他们的名字(瑞安,斯蒂芬和约翰)