![](/img/trans.png)
[英]Codeigniter how to echo more than one INNER JOIN from same table
[英]How to echo more than one row with same id
我有一個數據庫,它允許用戶 id 出現用戶想要的次數,例如 id = 1902 屬於這個 id 的項目是魚、面包、牛奶。 同一用戶在另一行 id = 1902 上具有相同的 id,屬於該 id 行的項目是胡椒、墊子、鼠標。
我想嘗試 output 用戶 ID 及其所有項目,但不知道要使用的代碼。
<?php
$xyttt = $_SESSION['email'];
$sql = "SELECT id FROM users where username = '$xyttt'";
$result = mysqli_query($db, $sql);
// fetch the resulting rows as an array
$investment = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach($investment as $invest){
// echo ($invest['id']);
$uidbb = ($invest['id']);
}
// free the $result from memory (good practise)
mysqli_free_result($result);
$uidbb = ($invest['id']);
$sql = "SELECT * FROM investment where userid = '$uidb'";
$result = mysqli_query($db, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["amount1"]. " " . $row["status"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
// free the $result from memory (good practise)
mysqli_free_result($result);
?>
我使用了這段代碼,但它正在獲取數據庫的所有行,包括其他用戶的 id,但我希望它只獲取在表上出現多次的特定 id 的所有行。
您可以從一個請求中獲取所有項目和用戶 ID SQL
SELECT * FROM investment where userid = (SELECT id FROM users WHERE username = ?)
或者
SELECT
*
FROM
investment INV
INNER JOIN
users U ON U.id = INV.userid
WHERE U.username = ?
對於 select 自定義行,您必須將( * )替換為表中的所需值
我不太了解您的問題:/
您可以使用內部聯接在一個查詢中執行此操作,如下所示:
SELECT
*
FROM
investment
INNER JOIN
users ON users.id = investment.userid
WHERE users.username = ?
這將從具有您提供的用戶名的investment
中獲取所有記錄。
您可以在此處閱讀有關內部聯接的更多信息: https://www.mysqltutorial.org/mysql-inner-join.aspx/
如您所見,我和其他答案都使用?
而不是帶有用戶名的變量。 那是因為我們使用參數化的准備好的語句,而不是直接將數據注入到查詢中。 我建議您也通讀一遍,因為這是在查詢中使用動態數據的推薦方式(並且在處理外部數據時是必要的)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.