The following code allows me to enter new records when there is no one id
to update, so far it works fine, but trying to update a record that does not exist, for example id
20
when in my data table I only have 5 records that go consecutively from id
1
until the id
5
.
<?php
if (isset($_POST['ajaxData'])) {
$id = $_POST["item_id"];
$nombre_cliente = $_POST["nombre_cliente"];
if (empty($_POST['nombre_cliente'])){
echo json_encode(['status'=> false, 'message'=> ["nombre_cliente" =>"Por favor, ingresé el nombre del cliente para continuar."]]);
exit;
}
if($id != '') {
$stmt = $con->prepare("UPDATE cliente
SET
nombre_cliente = ?
WHERE id_cliente = ?");
$stmt->bind_param("si",
$nombre_cliente,
$id
);
if ($stmt->execute()) {
echo json_encode(['status'=> true, 'message'=>"<strong>Los datos se actualizaron correctamente.</strong>"]);
exit;
} else {
echo json_encode(['status'=> false, 'message'=>"<strong>Lo sentimos, pero no podemos procesar su solicitud. Inténtalo más tarde.</strong>"]);
exit;
}
} else {
$stmtAdd = $con->prepare("INSERT INTO cliente (nombre_cliente) VALUES (?)");
$stmtAdd->bind_param("s",$nombre_cliente);
if ($stmtAdd->execute()) {
echo json_encode(['status'=> true, 'message'=>"<strong>Nuevo cliente registrado correctamente.</strong>"]);
exit;
} else {
echo json_encode(['status'=> false, 'message'=>"<strong>Lo sentimos, pero no podemos procesar su solicitud. Inténtalo más tarde.</strong>"]);
exit;
}
}
}
?>
So when it sent the update saying id 20
that it doesn't exist, ajax, it gives me a statement that the data was updated correctly, when this shouldn't happen, because it's data that doesn't exist, it should send me the message false
, and not the true
.
This is my ajax code:
$(function() {
var frm = $('#ajaxData');
frm.submit(function(e){
//$('.error', '#resetform').remove();
e.preventDefault();
var formData = frm.serialize();
formData += '&' + $('#submit_data').attr('name') + '=' + $('#submit_data').attr('value');
var url = "update_cliente.php";
$.ajax({
type: frm.attr('method'),
url: url,
data: formData,
})
.done(function(data) {
let res = JSON.parse(data);
// si es true el estado
if(res.status){
$('.success').fadeIn();
$('.success').html(res.message).delay(8000).fadeOut(8000);
$(frm)[0].reset();
$(frm).hide();
setTimeout(function(){
location.href = 'cliente.php';
},9000);
} else {
for (let name in res.message) {
$('.error').remove();
let msg = '<span class="error">' + res.message[name] + '</span>';
$(msg).insertAfter($('[name=' + name + ']', '#ajaxData'));
$('.error').fadeIn().delay(5000).fadeOut(5000);
}
}
})
.fail(function() {
$('.warning').fadeIn();
$('.warning').html(textStatus).delay(3000).fadeOut(3000);
})
});
});
How can I solve this error? Is it an Ajax error or an PHP code approach?
The problem is that this alone does not work to know if an update has occurred:
The method
execute()
returnstrue
when there is no error executing a query. But a query with aWHERE
whose criteria isn't met isn't a bad query, it's just a query that doesn't return anything or does nothing or doesn't really change anything.That's why you should also check the affected rows with
affected_rows
.The same goes for the
INSERT
and theDELETE
. Only when it isaffected_rows
greater than the , the or an eventual .0
UPDATE
INSERT
DELETE
To apply what we've said, you can modify your
UPDATE
e blocksINSERT
like this:In the
UPDATE
:And in the
INSERT
:It should be said that a
UPDATE
that was based on the same data that already exists would also return0
inaffected_rows
. For example, if the current name isPedro
and you send it to update it,Pedro
the query is tried, but it returns0
affected rows. The DBMS is not stupid, I imagine that somehow it verifies that the data to be set as new is different from the one that already exists before confirming the UPDATE. Of course, if there are other column(s) to update, with a value other than those that exist, even ifPedro
it is the same, the UPDATE will occur because there is something different in that other column(s).In any case, perhaps it would be convenient to avoid sending useless queries to the server from the client, such as ordering to update a record that does not exist. But that is another business...