Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQLi echo data in array without doing a while loop

Tags:

php

mysqli

When using MySQLi, do I have to perform a kind of while loop where the actual data from the query is put into a variable array?

$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);

// Check if able to connect to database
if ($conn->connect_error) {
  trigger_error("Database connection failed: "  . $conn->connect_error, E_USER_ERROR);
}

$sql = "SELECT name FROM users WHERE email = '$email'";

$rs = $conn->query($sql);
$numRows = $rs->num_rows();

I always do the following:

$rs->data_seek(0);
while($row = $rs->fetch_assoc()) {
    $name = $row['name'];
}

echo $name;

Isn't there a much more convenient way to echo the data form the query when there is only one row?

like image 403
Andreas Avatar asked Aug 16 '26 08:08

Andreas


1 Answers

If there is only one row, you don't need the loop. Just do:

$row = $rs->fetch_assoc();
$name = $row['name'];
like image 184
Amal Murali Avatar answered Aug 18 '26 22:08

Amal Murali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!