使用mysqli预处理语句返回多维关联数组

时间:2012-12-26 18:11:38

标签: php mysql mysqli

我正在尝试使用格式

从我的MySql数据库返回一个多维关联数组
$array[0]['user']
$array[0]['dateCompleted']
$array[0]['etc']
$array[1]['user']
$array[1]['dateCompleted']
$array[1]['etc']

...

这是我的代码:

$mysqli = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBDATABASE);
//Clean input
$idUser = trim($_SESSION['tmp01']);
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT user, dateCompleted, workType, workPrice FROM workDone WHERE user=? ORDER BY dateCompleted DESC");

/* bind parameters for markers */
$stmt->bind_param("i", $idUser);

$stmt->execute();

$data = $stmt->result_metadata();
$fields = array();
$row = array();
$rows = array();

$fields[0] = &$stmt;
$count = 1;

// this dynamically creates an array where each key is the name of the field. 
while ($field = mysqli_fetch_field($data)) {
    $fields[$count] = &$row[$field->name];
    $count++;
}

// this calls bind_result() to each member of this $row array  
call_user_func_array(array($stmt, 'bind_result'), $row);       //<--problem                      
while ($stmt->fetch())
    array_push($rows, $row);

$results = (count($rows) == 0) ? false : $rows;
//print_r($results);
return $results;

$stmt->close();

当我使用SQL语句"SELECT * FROM users ...")时,它可以正常工作,但我通过这样做会超出我的服务器内存。相反,我使用上面的代码,但它的作用是为每行返回一个相同的实例。

换句话说,如果我的MySQL数据库中有四个不同的行,它将返回第一行四次。

P.S。

我的服务器没有启用mysqlnd。

1 个答案:

答案 0 :(得分:2)

您的方法看起来是正确的,但您似乎将错误的参数传递给call_user_func_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(); //this is supposed to be outside the foreach
  foreach($currentrow as $key => $val) {
    $results[$i][$key] = $val;
  }
  $i++;
}

return $results;