簡體   English   中英

通過使用 php 比較 id 從另一個表中獲取數據

[英]Get data from another table by just comparing the id using php

如果另一個表中的 ID 和數據相同,我想通過調用從另一個表中獲取數據。

Table_1

Id  | name | lastname

1   | Fred | Moore

Table 2

Id  | table1_id 

1    |    1

我已經可以獲取表 1 的 ID 並將其存儲到我的表 2 中,但我想從表 1 中回顯姓名和姓氏。

例如,如果表 2 table1_id 等於 Table_1 Id,它將打印姓名和姓氏。

試試這個查詢

select table_1.name, table_1.lastname
from table_1
left join on table_2 on table_1.id = table_2.table1_id
<?php

$a = "Table_1";
$b = "Table_2 ";

$allItem = $cxn->query("SELECT * 
FROM $a  
INNER JOIN $b
ON $a.id = $b.id
WHERE $a.id  = 1);

$allItem = $allItem->fetchAll();

$lastName = $allItem["lastname"];
$name = $allItem["name"];

?>

也許它可以工作!

<?php 
$conn = mysqli_connect("localhost","username","password","database_name");
if(!$conn){
echo "Database Connection Failed!";
}

$query1 = mysqli_query($conn,"SELECT table1_id,first_name,last_name FROM table_1")or trigger_error(mysqli_error($conn));
if(mysqli_num_rows($query1)){
while($row1 = mysqli_fetch_array($query1)){
    $table1_id = $row1['table1_id'];
    $table1_first_name = $row1['first_name'];
    $table1_last_name = $row1['last_name'];

    $query2 = mysqli_query($conn,"SELECT table2_id,table1_id,first_name,last_name FROM table_2 WHERE table1_id='$table1_id' ORDER BY first_name,last_name ASC")or trigger_error(mysqli_error($conn)); //check table1_id from table2 AND table1_id from table1 if matched
    $row2 = mysqli_fetch_array($query2);
    $table2_first_name = $row2['first_name'];
    $table2_last_name = $row2['last_name'];

    echo "First Name: ".$table2_first_name."<br>"; //print first name
    echo "Last Name: ".$table2_last_name."<br>"; //print last name
  }
}
else{
echo "No Result Found.";
}
?>

暫無
暫無

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

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