0
I am deploying a system, where the customer, after buying an amount of credits, is inserted into his account in the database.
But I’m having a credit duplication problem in my PHP script.
<?php
header('Access-Control-Allow-Origin: *');
include '../../init.php';
$sql = "SELECT *, compras.id_usuario AS id_user_compra, compras.id AS id_compra FROM compras LEFT JOIN creditos ON creditos.id_usuario = compras.id_usuario WHERE compras.entregue = 'nao' AND compras.payment_status = 'Completed'";
$query = $mysqli->query($sql);
while ($ln = $query->fetch_array()){
$id_usuario = $ln['id_user_compra'];
$id_compra = $ln['id_compra'];
$creditos = preg_replace("/[^0-9\s]/", "", $ln['item_name']);
$sql_up = "UPDATE compras SET entregue = 'sim' WHERE id = '$id_compra'";
$query_up = $mysqli->query($sql_up);
$sql_ins = "INSERT INTO creditos (id_usuario, credito, debito) VALUES ('$id_usuario', '$creditos', '0')";
$query_ins = $mysqli->query($sql_ins);
}
?>
In my consultation above, he checks the purchases made, with certain conditions, but still, sometimes, it inserts a purchase 2 or 3x in the credits table.
Images to illustrate:
Shopping table:
Credit table:
How can I fix this problem?
Thanks in advance!
Your
select
must be returning more than one record.– Woss
Yes, he returns, because sometimes he has 2 or 3 purchases.
– Guilherme Lirio
So you’re making one
insert
within thewhile
that traverses the records. If there is more than one, it will be inserted more than once.– Woss
Wow, I ended up solving. I gave a LEFT JOIN in another table without needing... it was like this:
SELECT * FROM compras WHERE compras.entregue = 'nao' AND compras.payment_status = 'Completed'
Thank you!– Guilherme Lirio