从MySQLi预处理语句获取一个关联或数字数组不工作

时间:2014-01-21 05:46:09

标签: php arrays mysqli

我无法从mysqli预处理语句中获取关联或数字数组。我从代码中搜索和研究得到它,但它是不可能的。我根据所有代码生成此代码。我认为这是正确的,但无论如何它都不起作用:

    $id = '134610';
    $sql = "SELECT * FROM table WHERE id = ?";
    $stmt = $mysqli->stmt_init();
    $stmt->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();

            while ($array = $result->fetch_array(MYSQLI_ASSOC)) 
                               // or fetch_array(MYSQLI_NUM))
            print_r($array);

2 个答案:

答案 0 :(得分:2)

MYSQLI_ASSOC
    Columns are returned into the array having the fieldname as the array index.

MYSQLI_NUM
    Columns are returned into the array having an enumerated index.

http://php.net/manual/en/mysqli.constants.php

答案 1 :(得分:0)

我最终用该代码解决了它:

$id = '134610';
$sql = "SELECT * FROM table WHERE id = ?";
$stmt = $mysqli->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$array = self::bind_result_array($stmt);
for($i=0;$stmt->fetch();$i++)
    $ArrayOfArrays[$i] = self::getCopy($array);
$stmt->close();
return $ArrayOfArrays;

这两个功能:

public function bind_result_array($stmt)
{
$meta = $stmt->result_metadata();
$result = array();
while ($field = $meta->fetch_field())
{
    $result[$field->name] = NULL;
    $params[] = &$result[$field->name];
}

call_user_func_array(array($stmt, 'bind_result'), $params);
return $result;
}


public function getCopy($row)
{
return array_map(create_function('$a', 'return $a;'), $row);
}