无法从SQL结果php中获取实际值

时间:2016-03-22 21:44:22

标签: php mysql

我在php

中从我的sql查询中获取一些值时遇到了一些麻烦

这是我的PHP代码:

<?php
    include "init.php";

    $stmt = "SELECT email FROM Customer ";
    $result = $dbcon -> prepare($stmt);
    $result->execute();
    $result->store_result();
    while($result -> fetch()){
        // This line below works
        echo "Works";

        // This doesn't work
        echo $result['email'];
    }

?>

2 个答案:

答案 0 :(得分:0)

您需要使用bind_result()来检索查询返回的值。

include "init.php";

$stmt = "SELECT email FROM Customer ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
$result->bind_result($email);
while($result -> fetch()){
    // This line below works
    echo "Works";

    echo $email;
}

答案 1 :(得分:0)

首先,mysqli::prepare没有返回mysqli_result,它会返回mysqli_stmt。然后,您必须直接从mysqli_stmtfetch执行绑定变量,或者提取 mysqli_resultfetch。有几种方法可以做你想要的:

$qry = "SELECT email FROM Customer ";
$stmt = $dbcon->prepare($qry);
$stmt->execute();
$stmt->bind_result($email);  // Bind variable to statement
while($stmt->fetch())        // Iterate through statement
{
    // This line below works
    echo "Works";

    echo $email;
}

或者:

$qry = "SELECT email FROM Customer ";
$stmt = $dbcon->prepare($qry);
$stmt->execute();
$rslt = $stmt->get_result();       // Retrieve result set
while($row = $rslt->fetch_assoc()) // Iterate through result
{
    // This line below works
    echo "Works";

    echo $row['email'];
}

或者:

$qry = "SELECT email FROM Customer ";
$stmt = $dbcon->prepare($qry);
$stmt->execute();
$rslt = $stmt->get_result();                 // Retrieve result
$resArray = $rslt->fetch_all(MYSQLI_ASSOC)); // Convert to array
foreach ($resArray as $row)                  // Iterate through array
{
    // This line below works
    echo "Works";

    echo $row['email'];
}

按照我的习惯,我将错误处理作为读者的练习。