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;