PHP MySQLi echo data in array without doing a while loop

蹲街弑〆低调 提交于 2020-07-03 04:05:11

问题


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?


回答1:


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

$row = $rs->fetch_assoc();
$name = $row['name'];


来源:https://stackoverflow.com/questions/20176563/php-mysqli-echo-data-in-array-without-doing-a-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!