繁体   English   中英

如何从 SQL 中的两个表中获取百分比结果并用 php 显示?

[英]How to get percentage result from two table in SQL and show it with php?

Helo 朋友,我是 SQL 和 PHP 代码的新手,所以我需要你的帮助。

这是我的 SQL 表,其中包含字段( idproduct_nameid_categoryid_storeregular_pricesale_pricepercentage )。 有人可以帮我获得这个领域的价值“百分比。我需要使用这个公式:

  (($regular_price-$sale_price)/$sale_price)*100;

数据库

得到这个“百分比”值后,我需要显示所有表格字段。 在此示例中,我使用 INNER JOIN 显示其他 2 个表(产品类别和商店)中的值的名称。

<?php
   if(!require_once('conn.php'))
   {
       die("Error");
   }

   $upit = "SELECT * FROM artikal INNER JOIN category ON id_category = category.id
                                    INNER JOIN store ON id_store = store.id
        " ;
   $rezultat = $conn->query($upit);    
?>
                   <?php while($red = $rezultat->fetch_assoc()) { ?>
                   <tr>
                       <td><?= $red['product_name']; ?></td>
                       <td><?= $red['id_category']; ?></td>
                       <td><?= $red['id_store']; ?></td>
                       <td><?= $red['regular_price']; ?>$</td>
                       <td><?= $red['sale_price']; ?>$</td>
                       <td>**percentage discount I need here**</td>
                   </tr>
               <?php } ?>

谢谢你。

您将需要一个 php 代码来从$red['regular_price']$red['sale_price']数组中获取百分比值数组,因此您需要为百分比值设置一个空数组为

$red = ['regular_price' => [1,20,15,30],
        'sale_price'  => [32,50,64,98]
];
$precentage = [];
foreach ($red['regular_price'] as  $value) {
    foreach ($red['sale_price'] as $value1) {
        $precentage[] = (($value - $value1)/$value1) * 100;
    } 
}
echo '<pre>';
print_r($precentage);
echo '</pre>';

此代码导致以下百分比数组

在此处输入图像描述

注意:此处在数组中给出的值仅作为示例,因此您将结果数组作为负值,但通过使用相同的代码,您可以获得所需的值。

谢谢大家,我找到了答案。

$upit = "SELECT *,(((regular_price-sale_price)/regular_price)*100) as percentage FROM artikal INNER JOIN category ON id_category = category.id INNER JOIN store ON id_store = store.id " ;

暂无
暂无

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

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