0

我正在尝试从我的 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 数据库中有四个不同的行,它将返回第一行四次。

附言

我的服务器没有启用 mysqlnd。

4

1 回答 1

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;
于 2012-12-26T20:23:46.920 回答