Triggered by a web-hook of an e-commerce platform after a new order, I have to update a table with the order's details in a local system. So for the customer's info insertion part, I need to determine whether the customer is an existing one, or should be inserted as a new customer...
So, I wrote this piece of code:
sqlsrv_query($connection, sprintf("INSERT INTO z_web_users (UserID, OrderID, FirstName, LastName, Country, State, Region, Street, Zip, Phone, Email) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');",
sqlsrv_fetch_array(sqlsrv_query($connection, "SELECT COALESCE((SELECT DISTINCT UserId FROM z_web_users WHERE Email = '{$order->billing->email}'), (SELECT MAX(UserId) + 1 FROM z_web_users), 1) AS ID;"), SQLSRV_FETCH_ASSOC)['ID'],
$order->id,
$order->billing->first_name,
$order->billing->last_name,
$order->billing->country,
$states[$order->billing->state],
$order->billing->city,
$order->billing->address_1,
$order->billing->postcode,
$order->billing->phone,
$order->billing->email,
));
The problem is a got many suggestions that I should add some mechanism to ensure the returned MAX(UserId)
stays out of conflicts. Given that the table z_web_users
doesn't take any measures by its design, nor do I have any control over its design, what can I do in my code to ensure that?