简体   繁体   中英

PHP How to echo the result of a fetch outside a while-loop

I am new to Object Oriented 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 .

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 ). What I want: echo the result of the select query OUTSIDE a while loop. Just as it is possible in the old fashioned way (assuming there is only 1 result, therefore no while-loop necessary):

$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.

You can use $stmt->get_result() to do that, eg

$stmt->execute();
$result = $stmt->get_result();

$record = $result->fetch_assoc();
echo $record['username'];

Edit

Another method is to call fetch after bind_result

$stmt->bind_result($username);
$stmt->fetch()

echo $username;

Old fashion way:

print_r($record);

From the php manual: print_r

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM