I'm trying to compare the content of 2 arrays, basically I'm using a shopping cart and I need to check the prices of submitted forms against a database, the problem is when I have one incorrect price in the shopping cart it gives me an error message but when I have 1 correct price and 1 incorrect it continues with the checkout, I don't know what I'm doing wrong any help would be appreciated.
foreach ($cart->get_contents() as $item)
{
$item_id = $item['id'];
$item_name = $item['name'];
$item_price = $item['price'];
$item_qty = $item['qty'];
$connection = mysql_connect($dbhost,$dbuser,$dbpass) or die("Error connecting to mysql");
mysql_select_db($dbname);
$query = "select * from products where product_name = '$item_name'";
$result = mysql_query($query);
if (!$result) {
echo mysql_error();
}
while ($row = mysql_fetch_assoc($result)) {
$sql_price[] = $row['product_price'];
$qty[] = $row['product_qty'];
$name = $row['product_name'];
}
foreach($sql_price as $price) {
$price = $price;
if ($price !== $item_price) {
$valid_prices = false;
}else{
$valid_prices = true;
}
}
}
if ($valid_prices !== true)
{
// KILL THE SCRIPT
die($jcart['text']['checkout_error']);
}
The problem is you marking the cart entry as valid if the last array element of $sql_price
equals $item_price
.
Rewrite the loop as:
$valid_prices = true;
foreach($sql_price as $price) {
$price = $price;
if ($price !== $item_price) {
$valid_prices = false;
}
}
To prevent extra iterating, add a break
in the inner if
to stop the loop after finding an invalid price.
Or even this:
$valid_prices = (array_search($price, $sql_price) !== false);
You can have MySQL do all your work for you, even:
$query = 'select 1 from products where product_name = "' . mysql_real_escape_string($item_name) . '" and product_price = ' . (int)$item_price;
$result = mysql_query($query);
if (!$result) {
echo mysql_error();
}
if (mysql_num_rows($result) > 0) {
$valid_prices = true;
echo 'price is good!';
} else {
$valid_prices = bad;
echo 'price is bad!';
}
You are setting $valid_prices
to true or false on every loop iteration. So after the loop it only corresponds to the last item in the loop.
It might be better to set it to true outside (before) the loop, and then set it false when you find a bad case - that way it can't be set back to true. Alternatively you could just throw the error inside the loop as soon as you find the invalid price.
The main issue seems to be your inner foreach loop and the setting of valid_prices. Your loop continues through all prices so $valid_prices will depend on the last price only. You should break out of your loop as soon as you detect an invalid price.
A few other small things: