gwerner wrote: while($row2 = mysql_fetch_array($result2)) {
...
$result2a = mysql_query($query2a);
...
}
Using the results of a database query to run multiple database queries? Really bad code smell (not helped by the fact that $returnReason is checked multiple times within the loop even though it's constant throughout the loop). Almost certainly something that could be done entirely in the database (looks like a job for triggers and/or stored procedures).
if ($result3) {
header('Location: index.php');
}
Doesn't really have anything to do with processing order returns; shouldn't be here but somewhere back where the function was called from.
$returnQuantity = (int)$_POST['returnQuantity'];
$returnReason = (int)$_POST['returnReason'];
$returnId = (int)$_POST['returnId'];
Ditto. Pass these as parameters.
I feel like clothesdryer's lint trap at the moment, so this might not make sense and/or have additional gaping problems. But...
function orderReturn($quantity, $reason, $id)
{
$orderitems_update = "Update orderitems
set orderitems_quantity = orderitems_quantity - $quantity
where orderitems_id = $id";
if(!mysql_query($orderitems_update))
{
// The update failed for some reason. The original code when ahead and inserted a record in the returns table anyway,
// without saying anything about the failure.
// Me, I'm going to return false; remove the line if you want the old behaviour.
return false;
}
else
{
// Mmmm ... magic numbers...
if($reason == 1 || $reason == 4 || $reason == 5)
{
// There's probably a more efficient phrasing, but this is improvement enough for the nonce.
$product_update = "Update products
set products_inventory = products_inventory + $quantity
where products_id in (Select orderitems_productid
from orderitems
where orderitems_id = $id)";
if(!mysql_query($product_update))
{
// Another error situation.
return false;
}
}
}
$today = date('Y-m-d H:i:s'); // is this what you meant?
// Log the return
$returns_insert = "Insert into returns (return_productid, return_quantity, return_price, return_oid, return_reason, return_date)
Select orderitems_productid, $quantity, orderitems_price, orderitems_oid, $reason, '$today'
from orderitems
where orderitems_id = $id";
if(!mysql_query($returns_insert))
{
return false;
}
return true;
}
/*........................*/
$return_quantity = (int)$_POST['returnQuantity'];
$return_reason = (int)$_POST['returnReason'];
$return_id = (int)$_POST['returnId'];
mysql_query('Start Transaction');
if(orderReturn($return_quantity, $return_reason, $return_id))
{
mysql('Commit');
}
else
{
$error = mysql_error();
mysql('Rollback');
// deal with it...whatever the problem was, the error message is in $error.
}