如何在php中回显内部连接

mbskvtky  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(290)

我已经在mysql中测试了我的代码,而且它是有效的。我唯一的问题是,我不明白如何回显内部连接(以前从未使用过),而且我似乎无法在网上找到清晰的示例。
我需要把代码回显到 <table> 与数据库的连接(works):

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";

jslywgbw

jslywgbw1#

我不明白我是如何呼应一个内在的连接
这里的一个重要概念是,内部连接(或与此相关的任何连接)在同一个结果集中返回。您可以获得许多行,但这并不是由是否使用联接决定的。你可以简单地在结果集上循环;每次迭代为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>';
juzqafwq

juzqafwq2#

您的orders表似乎没有名为 Customer_Customer_ID . 所以我不知道你是怎么说的。
但是,请添加列 Customer_ID ,并将最后一行调整为:

INNER JOIN customer ON orders.Customer_ID=customer.Customer_ID";
svujldwt

svujldwt3#

按照我的评论,如果你想在内容中显示查询,只需做;

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;

相关问题