I have a datatable with user information and a column called ‘Bits’. There is a transfer function and I would like to transfer x amount of bits from the logged in user to the user they specify. I have the following function that works, but I would like to know if there is a better (simpler, cleaner, quicker?) way to do all of this, and possibly return the row of the first SQL statement at the end. I am not an advanced MySQL user by any means, but I am pretty sure there is a function I am missing that could make this much easier.
function transferBits($toid, $amount)
{
global $loggedInUser, $db;
$fromid = $loggedInUser->user_id;
$sql = "INSERT INTO `dl_Transfers` SET From_ID = '".$db->sql_escape($fromid)."',
`To_ID`='".$db->sql_escape($toid)."',
`Bits`='".$db->sql_escape($amount)."',
`When`=Now()";
$result = $db->sql_query($sql);
$sql2 = "UPDATE `dl_Users` SET Bits = Bits - '".$db->sql_escape($amount)."' WHERE `User_ID` = '".$db->sql_escape($fromid)."'";
$result2 = $db->sql_query($sql2);
$sql3 = "UPDATE `dl_Users` SET Bits = Bits + '".$db->sql_escape($amount)."' WHERE `User_ID` = '".$db->sql_escape($toid)."'";
$result3 = $db->sql_query($sql3);
}
I think you could hit the update in single query by joining on the previous record id from your insert on
dl_Transfers:Also as others stated in their comments, you should definitely use transactions here.