Heim > Fragen und Antworten > Hauptteil
P粉3216766402023-08-30 11:43:49
使用mysqli_fetch_row()
。试试这个,
$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id; $result = mysqli_query($conn, $query); $row = mysqli_fetch_row($result); $ssfullname = $row['ssfullname']; $ssemail = $row['ssemail'];
P粉6752585982023-08-30 09:34:29
当只需要单个结果时,不应使用循环。只需立即获取该行即可。
如果您需要将整行提取到关联数组中:
$row = $result->fetch_assoc();
如果您只需要一个值,从 PHP 8.2 开始:
$value = $result->fetch_column();
或者对于旧版本:
$value = $result->fetch_row()[0] ?? false;
以下是不同用例的完整示例
当要在查询中使用变量时,必须使用准备好的语句。例如,假设我们有一个变量 $id
:
PHP >= 8.2
// get a single row $sql = "SELECT fullname, email FROM users WHERE id=?"; $row = $conn->execute_query($query, [$id])->fetch_assoc(); // in case you need just a single value $sql = "SELECT count(*) FROM users WHERE id=?"; $count = $conn->execute_query($query, [$id])->fetch_column();
旧版 PHP 版本:
// get a single row $query = "SELECT fullname, email FROM users WHERE id=?"; $stmt = $conn->prepare($query); $stmt->bind_param("s", $id); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_assoc(); // in case you need just a single value $query = "SELECT count(*) FROM userss WHERE id=?"; $stmt = $conn->prepare($query); $stmt->bind_param("s", $id); $stmt->execute(); $result = $stmt->get_result(); $count = $result->fetch_row()[0] ?? false;
上述过程的详细解释可以在我的文章中找到。至于为什么必须遵循它,请参见这个著名的问题
在您的情况下,如果查询中没有使用变量,您可以使用 query()
方法:
$query = "SELECT fullname, email FROM users ORDER BY ssid"; $result = $conn->query($query); // in case you need an array $row = $result->fetch_assoc(); // OR in case you need just a single value $value = $result->fetch_row()[0] ?? false;