簡體   English   中英

SQL | 從查詢中獲取所有結果,而不僅僅是第一個

[英]SQL | Get all results from query not just the first

您好,我正在向 SQL 數據庫(在 php 中)發出請求,女巫看起來像這樣......

SELECT firstname FROM users WHERE job = '$jobL'

讓我們假設數據庫中有三個名為$jobL的用戶:Mike、Steve 和 Danny。

預期 Output: array("mike", "steve", "danny")

給定 Output: array("mike")

所以mikeusers表中的第一個結果。 SQL 只給我第一個結果,我想獲得與我的查詢匹配的所有結果,而不僅僅是第一個。

謝謝

編輯:它是一個 php function ...

function GetJobMembers($jobL) {     //Function to get all Members of an Job in an Array
    global $db;
 
    $AllWithJobSQL = $db->query("SELECT firstname FROM users WHERE job = '$jobL'");  
    $AllUsersWithJob = $AllWithJobSQL->fetch_assoc();


    return $AllUsersWithJob;
}

我用$jobL = groove //GTA RP Server stuff對其進行了測試

我的數據庫手動搜索:

在此處輸入圖像描述

好的,我已修復它...與 php 如何與 sql 一起使用有關。

你只需要設置fetch_all(MYSQLI_ASSOC);

像這樣:

function GetJobMembers($jobL) {     //Function to get all Members of an Job in an Array
    global $db;
 
    $AllWithJobSQL = $db->query("SELECT firstname FROM users WHERE job = '$jobL'");  
    $AllUsersWithJob = $AllWithJobSQL->fetch_all(MYSQLI_ASSOC);

    return $AllUsersWithJob;
}

fetch() 作為一個指針打開,准備好逐個遍歷數據(通常在 while 循環中)。

while($row= $AllWithJobSQL->fetch_assoc()) {
   echo $row["job"].PHP_EOL;;
}

在您的情況下,您應該使用 fetchAll()。 它一次獲取所有數據,無需打開任何指針,將其存儲在數組中。 當您希望一次將 SELECT 中的數千或數百萬行存儲到數組中時,如果您不希望有太多可能導致 memory 問題的結果,建議您使用此方法。

$AllUsersWithJob = $AllWithJobSQL-> fetch_all(MYSQLI_ASSOC);
return $AllUsersWithJob;

在這種情況下,$AllUsersWithJob 是一個包含所有查詢數據的關聯數組。 如果要讀取其中的行,可以實現一個循環來循環數組:

$resultado= GetJobMembers("doctor");
foreach ($resultado as $row){
    echo $row["job"].PHP_EOL;
}

使用fetch_all()將所有行作為二維數組獲取。 然后您可以使用array_column()從每一行中提取firstname索引。

您還應該使用准備好的語句來防止 SQL 注入。

function GetJobMembers($jobL) {     //Function to get all Members of an Job in an Array
    global $db;
    $stmt = $db->prepare("SELECT firstname FROM users WHERE job = ?");  
    $stmt->bind_param("s", $jobL);
    $stmt->execute();
    $result = $stmt->get_result();
    $AllUsersWithJob = $result->fetch_all(MYSQLI_ASSOC);

    return array_column($AllUsersWithJob, 'firstname');
}

我認為您使用了錯誤的 fetch method.Fetch,返回匹配的第一行。

你的代碼應該是這樣的:

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);

有關更多信息,您可以在此處查看

如果您使用的是 mysqli 您的代碼應該是這樣的。

$AllWithJobSQL = $mysqli->query("SELECT firstname FROM users WHERE job = '$jobL'");

$AllUsersWithJob = $AllWithJobSQL ->fetch_all(MYSQLI_ASSOC);

return $AllUsersWithJob;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM