I want to get data from another table by just calling if the ID and data from another table is the same.
Table_1
Id | name | lastname
1 | Fred | Moore
Table 2
Id | table1_id
1 | 1
I can already get and store the table 1 id to my table 2, but i want to echo the name and lastname from the table 1.
eg if table 2 table1_id is equal to Table_1 Id it will print the name and lastname.
Try this query
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"];
?>
Maybe it could work!
<?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.";
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.