-4
I have a php form to include records in Mysql, when sending the record duplicates triples the times quadriplica records in mysql, in a topic I saw the suggestion to disable the button, preventing the user to click on the record more than once without wanting to , I tried to do this procedure, but even so the records sometimes duplicate, it may be something with PHP session, I realized that this occurs when it is slow on the internet. It follows the code: page of the form:
<!--Formulario de cadastro-->
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email </label>
<input type="email" class="form-control" id="Email" aria-describedby="email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="Password" placeholder="Password">
</div>
<button type="submit" id="Enviar_cadastro_email" class="btn btn-primary">Enviar</button>
</form>
<!--JS-->
<script>
$(document).ready(function () {
$('#Enviar_cadastro_email').click(function () {
$('#Enviar_cadastro_email').prop('disabled', true);
var vEmail = document.getElementById("Email").value;
var vPassword = document.getElementById("Password").value;
var action = "Incluir";
$.ajax({
url: "usuario.php",
method: "POST",
data: {
action: action,
vEmail: vEmail,
vPassword: vPassword
},
success: function (data) {
CarregarListagem();
}
});
}
});
});
</script>
<!--PHP - back -->
<?php
include "../confi.php";
if (isset($_POST["action"])) {
if ($_POST["action"] == "Incluir") {
$statement = $connection->prepare("
INSERT INTO usuario (
usuario_email,
usuario_senha
)
VALUES(
:usuario_email,
:usuario_senha
)
");
$result = $statement->execute(
array(
':usuario_email'=> $_POST["vEmail"],
':usuario_senha'=> $_POST["vPassword"]
)
);
if (!empty($result)) {
echo 'Usuário inserido com sucesso!';
} else {
echo 'Erro ao inserir usuário!';
}
}
}
that is my code
If you put a validation before entering the database, which checks if the data already exists, only to send it, the problem continues? Normally, in the database configuration itself, I create unique keys where I don’t want a data to repeat itself, so even though the code for any reason, "tries" to duplicate, the database itself will reject the insertion. If it is feasible to change the database, take a look at
UNIQUE
.– Weslley Araújo
A hunch, I suppose the button
Enviar
is firing two Ubmit events. Here<button type="submit"
change to<button type="button"
and see if it stops duplicating the insertion of records.– Augusto Vasques