[英]PHP How to echo the result of a fetch outside a while-loop
I am new to Object Oriented PHP. 我是面向对象PHP的新手。 Currently I am making a login script and am stuck at fetching & echo'ing the results.
目前我正在制作一个登录脚本,我一直在抓取并回显结果。 This is my script:
这是我的脚本:
$stmt = $db->mysqli->prepare("select User from `users` where User = ? AND Password = ?");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->store_result();
$num = $stmt->num_rows;
$stmt->bind_result($username);
if ( $num !== 1 ) {
echo 'no result';
} else {
echo 'Your username: '. $username ;
}
$stmt->close();
As you can see I am not fetching a result in the script above. 正如您所看到的,我没有在上面的脚本中获取结果。 I tried using
$stmt->fetch()
in a while-loop prior to the $num !== 1
. 我尝试在
$num !== 1
之前的while循环中使用$stmt->fetch()
。
However, the result of the fetching is "stored" as an array (I think), even though inside the while loop you don't use an array (just $username
). 但是,获取的结果被“存储”为一个数组(我认为),即使在while循环中你不使用数组(只是
$username
)。 What I want: echo the result of the select query OUTSIDE a while loop. 我想要的:回显选择查询OUTSIDE while循环的结果。 Just as it is possible in the old fashioned way (assuming there is only 1 result, therefore no while-loop necessary):
就像有可能以老式的方式(假设只有1个结果,因此没有必要的while循环):
$result = mysqli_query( $conn, $query );
$record = mysqli_fetch_array( $result );
echo $record['username'];
You need to accses to object variable: 你需要考虑对象变量:
echo $stmt->User;
Or you can save variable for later: 或者您可以保存变量以供日后使用:
$user = $stmt->User;
After ending of your loop your $user
will hold the value. 循环结束后,
$user
将保留该值。
You can use $stmt->get_result()
to do that, eg 您可以使用
$stmt->get_result()
来执行此操作,例如
$stmt->execute();
$result = $stmt->get_result();
$record = $result->fetch_assoc();
echo $record['username'];
Edit 编辑
Another method is to call fetch after bind_result 另一种方法是在bind_result之后调用fetch
$stmt->bind_result($username);
$stmt->fetch()
echo $username;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.