[英]Not able to get the actual values from SQL result php
I am having some trouble getting some values from my sql query in php 我在从php的sql查询中获取一些值时遇到麻烦
This is my php code: 这是我的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'];
}
?>
You need to use bind_result()
to retrieve the values returned by the query. 您需要使用
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;
}
To start, mysqli::prepare
doesn't return a mysqli_result
, it returns a mysqli_stmt
. 首先,
mysqli::prepare
不返回mysqli_result
,而是返回mysqli_stmt
。 You then have to execute that mysqli_stmt
and either fetch
directly from it into a bound variable, or extract a mysqli_result
and fetch
from that. 然后,您必须执行该
mysqli_stmt
,或者直接从其中fetch
绑定变量,或者提取 mysqli_result
并从中fetch
。 There are several ways to do what you want: 有几种方法可以做您想要的事情:
$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;
}
Or: 要么:
$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'];
}
Or: 要么:
$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'];
}
As is my custom, I leave error handling as an exercise for the reader. 按照我的习惯,我将错误处理作为练习留给读者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.