[英]How to echo INNER join in PHP
我已经在MySQL中测试了我的代码,并且可以正常工作。 我唯一的问题是我不明白如何回应INNER JOIN(以前从未使用过),而且我似乎无法在网上找到清晰的示例。
我需要将代码回显到与数据库的<table>
连接中(有效) :
include 'db_connection1.php';
$conn = OpenCon();
echo "Connected Successfully";
数据库连接将转到:
<?php
function OpenCon()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "admin";
$db = "theDBname";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or
die("Connect failed: %s\n". $conn -> error);
return $conn;
}
function CloseCon($conn)
{
$conn->close();
}
?>
码:
$sql = "SELECT orders.Order_ID AS OrderID,
customer.First_Name AS FirstName,
customer.Last_Name AS LastName,
orders.Order_Date AS OrderDate
FROM Orders
INNER JOIN customer ON orders.Customer_Customer_ID=customer.Customer_ID";
根据我的评论,如果您想在内容中显示查询,只需执行;
echo $sql;
(我知道这并不是一个完整的答案-这是写下来的一种形式)
解释后编辑
根据您的评论,您希望结果在表格中吗?
所以...
<?php
$table = "<table><tr><th>Order ID</th><th>First Name</th><th>Last Name</th><th>Order Date</th></tr>";
// Set up DB connection
$conn = new MySqli("db_hostname", "db_user", "db_pass", "db_name");
// Excecute the query
$result = $conn->query("SELECT orders.Order_ID AS OrderID,
customer.First_Name AS FirstName,
customer.Last_Name AS LastName,
orders.Order_Date AS OrderDate
FROM Orders
INNER JOIN customer ON orders.Customer_Customer_ID=customer.Customer_ID");
// For each row, add the results to a table string using concatenate (.=)
while ($row = $result->fetch_assoc())
{
$table .= "<tr>";
$table .= "<td>{$row['OrderID']}</td>";
$table .= "<td>{$row['FirstName']}</td>";
$table .= "<td>{$row['LastName']}</td>";
$table .= "<td>{$row['OrderDate']}</td>";
$table .= "</tr>";
}
$table .= "</table";
print $table;
您的订单表似乎没有名为Customer_Customer_ID
的列。 因此,我不知道您如何声明查询的工作原理。
但是,添加一列Customer_ID
,并将最后一行调整为:
INNER JOIN customer ON orders.Customer_ID=customer.Customer_ID";
我不明白我如何回应内在的加入
这里的重要概念是INNER JOIN(或与此相关的任何联接)都返回相同的结果集。 您可以获得许多行,但这不是通过使用联接来确定的。 您可以简单地遍历结果集。 每次迭代为1行。
<?php
...
$results = $conn->query("SELECT orders.Order_ID AS OrderID,
customer.First_Name AS FirstName,
customer.Last_Name AS LastName,
orders.Order_Date AS OrderDate
FROM Orders
INNER JOIN customer ON orders.Customer_Customer_ID =
customer.Customer_ID");
print '<table border="1">';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["OrderID"].'</td>';
print '<td>'.$row["FirstName"].'</td>';
print '<td>'.$row["LastName"].'</td>';
print '<td>'.$row["OrderDate"].'</td>';
print '</tr>';
}
print '</table>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.