mysqli获取结果为assoc数组

时间:2016-02-16 09:44:18

标签: php mysql

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = $mysqli->prepare($query)) {

    /* execute statement */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)\n", $name, $code);
    }

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();

有人可以帮助我这个语句/语法吗?我希望结果为关联数组(由fieldname索引),并且不想写这个" $stmt->bind_result($name, $code);"声明。感谢

3 个答案:

答案 0 :(得分:2)

由于您实际上并未使用任何参数,例如?,因此您根本不需要执行->prepare

所以你可以使用->query()->fetch_assoc()机制

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

$result = $mysqli->query($query)

if ( $result === FALSE ) {
    echo $mysqli->error;
    exit;
}

/* fetch values */
while ($row = $result->fetch_assoc()) {
   printf ("%s (%s)\n", $row['name'], $row['code']);
}

发表评论后

如果您必须保留准备

,这是另一种选择
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

// there seems to be some confusion in the manual as to 
// whether this next statement is needed or not
// see if that helps

$stmt = $mysqli->stmt_init();

if ($stmt = $mysqli->prepare($query)) {   

    /* execute query */
    if (!$stmt->execute()) {
        echo $stmt->error;
        exit;
    }

    $result = $stmt->get_result();

    /* fetch values */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row['name'], $row['code']);
    }

} else {
    echo 'Failed to prepare statement';
    exit;
}

$stmt->get_result()的调用基本上将mysql_stmt对象转换为mysql_result对象

答案 1 :(得分:0)

试试这个。

    $stmt = $mySqli->query($query);
    $countries = mysqli_fetch_all($stmt, MYSQLI_ASSOC);
    $stmt->close();

答案 2 :(得分:0)

试试这个:

while ($stmt->fetch(PDO::FETCH_ASSOC)) {
    printf ("%s (%s)\n", $name, $code);
}