![](/img/trans.png)
[英]Display data from two different tables in the index() using cakephp.
[英]Display data from two different tables using php
我在MySQL數據庫中有兩個表,我想使用php搜索它們,這是我能夠做到的。 但是,當我要顯示網站中表中的數據時,問題就來了。 這兩個表具有不同的字段名稱和不同的字段數。 是否有可能按索引或類似方式顯示行。 非常感謝你的幫助。
那是我的代碼php代碼:
<?php
//variables to connect to db
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project";
$lookingto = $_POST["sendTo"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//getting user details from data base
$sql = "SELECT * FROM ".$lookingto."";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Your search results</th></tr>";
echo "<tr><td><h3>Name</h3></td><td><h3>ID</h3></td></tr><tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td>".$row["make"]."</td><td>".$row["model"]."</td></tr>";
}
echo "</table>";
} else {
echo $lookingto;
echo "No details found, please check your details and try again";
}
$conn->close();
?>
聯接查詢:
Select * from Table1
LEFT JOIN Table2 on Table2.col1 = Table1.colb
where Table1.cola = $var
其中$ var是要搜索的id
,兩個表通過col1
(表2)和colb
(表1)鏈接。
您可以更改columns/tables
和類型join
按您的使用情況。
來源: 代碼項目-SQL聯接的可視表示
如果兩個表之間使用了任何關系鍵,則可以使用聯接使用該外鍵獲取數據。
E,g select table1.*, table2.* from table1 LEFT JOIN table2 on table2.col2=table1.col1 where table1.col=$variable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.