简体   繁体   English

从外键表中获取第一张图像

[英]Fetch first image from foreign key table

I have created a posting system with the help of the thread here: Add a product with details (name,quantity,multiple images) and retrieve them in another page In the following I want to make the last 8 entries of the table show on the index page. 我已经在这里的线程帮助下创建了一个发布系统: 添加一个包含详细信息(名称,数量,多幅图像)的产品,并在另一个页面中检索它们。在下面,我想使表格的最后8个条目显示在索引页。 I was able to display the name of the product and the other features in the first table for each one, but I would like to display the first image associated with the product_id of that post (* images have unique id but product_id is foreign key for the primary key in the first table - product_id from products). 我能够在每个表格的第一个表格中显示产品名称和其他功能,但是我想显示与该帖子的product_id相关联的第一张图片(*图片具有唯一的ID,但product_id是该产品的外键第一个表中的主键-来自产品的product_id)。 Someone help me with php script? 有人用PHP脚本帮助我吗?

php code: php代码:

$sql = SELECT id, name, quantity, description FROM products ORDER BY id DESC LIMIT 8;
$result = mysqli_query($connection, $sql);

html code: html代码:

 if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
            echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["quantity"]. "<br>";
            echo "<a href='getProduct.php?id=$row[id]'>See Product</a> <br>";
    }
} else { echo "0 results";
}

Tables

CREATE TABLE `products` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `quantity` int(11) DEFAULT NULL,
  `description` varchar(150) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `products_images` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `product_id` int(11) unsigned DEFAULT NULL,
  `filename` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `product_id` (`product_id`),
  CONSTRAINT `products_images_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Sorry...is my first post on stackoverflow ... 抱歉...是我关于stackoverflow的第一篇文章...

There are two ways you could go to retrieve the image. 您可以通过两种方法来检索图像。 The first one would be to run another query for each image, while you're iterating through your results 第一个是在遍历结果的同时对每个图像运行另一个查询

Something like this: 像这样:

<?php

$sql = "SELECT id, name, quantity, description FROM products ORDER BY id DESC LIMIT 4";
$result = mysqli_query($connection, $sql);

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["quantity"]. "<br>";
        echo "<a href='getProduct.php?id=$row[id]'>See Product</a> <br>";
        // load the image
        $imageResult = mysqli_query($connection, "SELECT filename FROM products_images WHERE product_id = " . mysqli_real_escape_string($connection, $row["id"]) . " LIMIT 1");
        if (mysqli_num_rows($imageResult) == 1) {
            $imageRow = mysqli_fetch_assoc($imageResult);
            echo "the image filename is: " . $imageRow["filename"];
        }

    }
} else { echo "0 results"; }

The second option, which I would prefer, is to "Join" the second table, which could look like this: 我希望使用的第二个选项是“加入”第二张表,它看起来可能像这样:

<?php

$sql = "SELECT p.id, p.name, p.quantity, p.description, i.filename FROM products p LEFT JOIN product_images i on i.product_id = p.id ORDER BY p.id DESC LIMIT 4";
$result = mysqli_query($connection, $sql);

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["quantity"]. "<br>";
        echo "<a href='getProduct.php?id=$row[id]'>See Product</a> <br>";
        if ($row["filename"]) {
            echo "the image filename is: " . $row["filename"];
        }

    }
} else { echo "0 results"; }

I'd recommend you to read about joins in SQL first (there are numerous resources, ex: https://www.w3schools.com/sql/sql_join.asp , https://en.wikipedia.org/wiki/Join_(SQL) or http://www.sql-join.com/ ) 我建议您先阅读有关SQL中的联接的信息(有很多资源,例如: https : //www.w3schools.com/sql/sql_join.asp,https : //en.wikipedia.org/wiki/Join_( SQL)http://www.sql-join.com/

The next thing, I'd recommend to you is securing your database queries against a thing called SQL Injection . 接下来,我建议您针对称为SQL Injection的事物保护数据库查询。 In the first example I've added mysqli_real_escape_string($connection, $row["id"]) to do this. 在第一个示例中,我添加了mysqli_real_escape_string($connection, $row["id"])来执行此操作。 A better way (and in general you should use this technique to write database queries!) is to use prepared statements. 更好的方法(通常应该使用这种技术编写数据库查询!)是使用准备好的语句。 You can read about them ex. 您可以阅读有关它们的信息。 here: https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection 此处: https : //websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection

The next thing I'd like to point out, is that you don't need to write every thing in PHP. 我想指出的第二件事是,您不需要用PHP编写所有东西。

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
            echo "id: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["quantity"]; ?><br>
            <a href="getProduct.php?id=<?php echo $row[id]; ?>">See Product</a><br>
    <?php }
} else { echo "0 results"; }

Is perfectly valid! 完全有效! No need to output all html code using echo just "pause" the php stuff in between. 无需使用echo即可输出所有html代码,而只需“暂停”其间的php内容。

Finally I'd like to introduce you to https://phptherightway.com/ which does not only cover the "basics" but also points you to further resources. 最后,我想向您介绍https://phptherightway.com/ ,它不仅涵盖了“基础知识”,还向您指出了更多资源。

If you want to recover the image associated with the product, you must do it using the WHERE cluase or using the JOINS for example: 如果要恢复与产品关联的图像,则必须使用WHERE克隆或使用JOINS来进行恢复,例如:

SELECT 
    id, 
    name, 
    quantity, 
    description 
FROM products, image 
WHERE products.id = image.id 
ORDER BY id DESC 
LIMIT 4;

or also 或者也

SELECT 
    id, 
    name, 
    quantity, 
    description 
FROM products 
NATURAL JOIN image 
ORDER BY id DESC 
LIMIT 4;

But that means that the idImage must be as a foreign key in the products table 但这意味着idImage必须作为products表中的外键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM