How can I show the percentage in percent %
of how much is the value that the product discount is being applied with the current price and the previous price.
Example:
If in the database I have the following records in the tableproducts
id_pro price price_old
1 50.00 100.00
The next message to show on the card would be $50.00 / 50% discount
I perform the query as follows:
Note: The query code
PHP
is above theHTML
if (isset($_GET['id'])){
$id = $_GET['id'];
$sql = "SELECT * FROM products WHERE url='".$id."'";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
$id = $row['id_pro'];
$price = $row['price'];
$price_old = $row['price_old'];
}
}
}
I show the results of the query as follows, within any content HTML
.
<?php echo $price; ?>
My idea is to be able to take the value of the two variables $price
and $price_old
through them show what percentage of discount is being made.
Note: Always taking into account whether or not there is a previous price registered in the table, some products will not have a previous price registered in that case there would not be a discount percentage in
price_old
the table columnproducts
My idea would be something like this, but I have problems in the approach of the code PHP
to show the percentages taking into account the current price and the previous price.
}else{
echo "Aquí el porcentaje -> 50% de descuento";
}else {
echo "No existe descuento -> En este caso no se mostrara un texto, quedara un echo vació";
}
You can use the simple rule of three to calculate the percentage, where the crossed numbers are multiplied and divided by the one that remains alone.
Assuming that we have a product with a previous price of $120 and a current price of $60, the calculation would be as follows:
The value of
x
is only the percentage difference between the two prices. To know the discount of the product, it only remains to calculate the difference between100%
andx
.In PHP it would look like this: