PHP MySQLi在数组中回显数据而不进行while循环

时间:2013-11-24 15:55:58

标签: php mysqli

使用 MySQLi 时,是否必须执行一种while循环,将查询中的实际数据放入变量数组?

$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();

我总是这样做:

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

echo $name;

当只有一行时,是否有一种更方便的方法来回显查询数据?

1 个答案:

答案 0 :(得分:8)

如果只有一行,则不需要循环。只是做:

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