Destiny Destiny - 7 months ago 27
PHP Question

PHP - Average input form with value in database error Unsupported operand types

I want to average the value from input form price with price from database.

so I tried to edit my code like this :

//input form
$productName=$_POST['productName'];
$buyingPrice=$_POST['buyingPrice'];
$sql2="SELECT product_name FROM products WHERE product_name='$productName'";
$result2=mysqli_query($connection, $sql2);

//process to average
if($result2=true){
$sql2="SELECT buying_price FROM products WHERE product_name='$productName'";
$result=mysqli_query($connection, $sql2);
$beli = mysqli_fetch_assoc($result);
$beli_new=$_POST['buyingPrice'];
$ratabeli=$beli+$beli_new/2; //I get the error on this line
$sql = "UPDATE products SET buying_price='$ratabeli' WHERE product_name='$productName'";
echo "<script type='text/javascript'>alert('Stok $productName dirata-ratakan!');</script>";
}


reference from this link, I've add this code
$ratabeli=(int)$beli+(int)$beli_new/2;


but the average isn't working, and my data just output first price,

Can anyone give me any guidance on this case please

Answer Source

1) $result2=true is assigning value true to $result2 .comparison should be== or ===

2) $beli is array you need to extract the value from it.

use like this

$ratabeli=($beli['buyingPrice']+$beli_new)/2;

Much care your code looks. sql injection possibilities .try to use prepared statement or PDO