如何連接到表格並顯示其內容? (MySQL 和 PHP)
P粉738821035
P粉738821035 2024-04-03 09:55:31
0
1
436

我有兩個 mysql 表(產品和類別)。我在兩個表中都有一些模擬數據。現在我需要以某種方式將類別附加到產品上。例如 - ID 為 1 的產品應傳回以下內容:

| product name | category   |
| Monitor      | Technology |

我知道我以前已經這樣做過,但今天我似乎找不到解決方案。

編輯 這是我到目前為止所擁有的。連接運行良好,我可以在表格中顯示數據。

<?php
// Include database connection
include("connection.php");

// Create variables for later use
$db = $conn;
$tableName = "Produkte";
$columns= ['id_product', 'name_product'];

// Create variable to use in index.php
$fetchData = fetch_data($db, $tableName, $columns);

// The function below feteches data from the tables specified and checks if the colums are emtpy by any chance.
function fetch_data($db, $tableName, $columns) {
    // Check db connection
    if (empty($db)) {
        $message= "Database connection error";
    }
    // Check if the columns variable is empty and not an array by any chance
    elseif (empty($columns) || !is_array($columns)) {
        $message="Product Name must be defined in an indexed array";
    }
    // Check if table name is empty
    elseif (empty($tableName)) {
        $message= "Table Name is empty";
    }
    // Else proceed as usual.
    else {
        $columnName = implode(", ", $columns);
        // The query needs to be repalced. Today my SQL stuff is leaving me a bit.
        $query = "SELECT p.".$columnName." AS product, c.name_category FROM $tableName p JOIN Kategorie c ON c.id_";
        $result = $db->query($query);
        if ($result== true) {
            if ($result->num_rows > 0) {
                $row= mysqli_fetch_all($result, MYSQLI_ASSOC);
                $message= $row;
            }
            else {
                $message= "No Data Found";
            }
        }
        // Throw error if error occures
        else{
            $message= mysqli_error($db);
        }
    }
    return $message;
}

表格 products 只有 2 個欄位。 id 欄位和 product_name 欄位。

P粉738821035
P粉738821035

全部回覆(1)
P粉014293738

基本技術有所不同:

// create DBquery using JOIN statement 
$query = "
SELECT 
    p.name AS product, c.name AS category 
FROM products p
JOIN categories c ON c.id = p.category_id;";

// get DB data using PDO
$stmt = $pdo->prepare($query);
$stmt->execute();

// show table header
printf('| product name | category   |' . PHP_EOL);

// loop for output result as table rows
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    printf('| %-12s | %10s |' . PHP_EOL, $row['product'], $row['category']);
}

線上嘗試

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!