簡體   English   中英

使用PHP從多個MySQL表查詢

[英]Query from multiple MySQL tables using PHP

我具有以下功能,該功能可從表格發票中提取發票數據,但是如何從與發票編號匹配的客戶表格中獲取數據:

所以我想需要* from customers tables where invoice = invoice獲取* from customers tables where invoice = invoice

的PHP

// the query
    $query = "SELECT * FROM invoices ORDER BY invoice ASC";

    // mysqli select query
    $results = $mysqli->query($query);

    // mysqli select query
    if($results) {

        print '<table class="table table-striped table-bordered" id="data-table" cellspacing="0"><thead><tr>

                <th><h4>Invoice</h4></th>
                <th><h4>Customer</h4></th>
                <th><h4>Issue Date</h4></th>
                <th><h4>Due Date</h4></th>
                <th><h4>Status</h4></th>
                <th><h4>Action</h4></th>

              </tr></thead><tbody>';

        while($row = $results->fetch_assoc()) {

            print '
                <tr>
                    <td>'.$row["invoice"].'</td>
                    <td>'.$row["customer_name"].'</td>
                    <td>'.$row["invoice_date"].'</td>
                    <td>'.$row["invoice_due_date"].'</td>
                    <td>test</td>
                    <td><a href="invoice-edit.php?id='.$row["invoice"].'" class="btn btn-primary">Edit</a> <a data-invoice-id="'.$row['invoice_id'].'" class="btn btn-danger delete-product">Delete</a></td>
                </tr>
            ';

        }

        print '</tr></tbody></table>';

    } else {

        echo "<p>There are no invoices to display.</p>";

    }

嘗試這個..

 $query = "SELECT c.customer_name, i.* FROM invoices as i JOIN customers as c ON i.customer_id = c.id ORDER BY i.invoice ASC";

這將為您提供所需的客戶名稱。

請參閱http://w3schools.com/sql/sql_join.asp

$query = "SELECT * 
          FROM Invoices I, Customers C 
          WHERE I.invoice = C.invoice
          ORDER BY C.invoice ASC";

如果您希望不使用聯接的語句。

首先,通常最好將您的密鑰包含在您select的密鑰中(並且更容易排除故障),而不是* 但是,假設這些是您的字段,則可以使用JOIN進行連接,如下所示:

SELECT * 
FROM invoices i
JOIN customer c
ON c.invoice = i.invoice
ORDER BY i.invoice

假設您在每個表上都有一個公用鍵(如您所建議的那樣)是發票(這是使用數據庫而不是平面文件的巨大優勢),則可以將它們連接在一起( ic只是快捷方式,使其更易於閱讀查詢)。

您還可以在ON行后使用WHERE修改此WHERE以縮小結果范圍,例如這樣(假設您要查找編號為12345的特定發票

SELECT * 
FROM invoices i
JOIN customer c
ON c.invoice = i.invoice
WHERE i.invoice = 12345
ORDER BY i.invoice

SQL非常強大。 如果您想了解更多信息,可以在此站點上找到一些很棒的教程: http : //www.w3schools.com/sql/

如果要在查詢中調用此方法(使用第一個示例),則可以像以前一樣進行操作,如下所示:

 while($row = $results->fetch_assoc()) {
        echo $row["invoice"];

}

編輯:將來最好在select中聲明您的密鑰。 假設customer_name在customer表中,則可以在select中將其稱為c.customer_name 但是,這是與通配符一起從兩個表中獲取所有內容的方法。 將查詢更改為此:

SELECT i.*, c.*
FROM invoices i
JOIN customer c
ON c.invoice = i.invoice
ORDER BY i.invoice

暫無
暫無

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

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