I'm in a course in udemy about web development and I've found that the code showing have some errors (i'm not the only one), so after more than a month without answer from the tutor I would live if you could help me.
This code is about making a log in to the "admin" área, creating new admins, editing and deleting them. The code was working fine until the "eliminar" (delete) was added, it pop up the alert when I click delete, but dont delete the items in the MySQL and that's not the only problem. When i tried to log in, it seems like it didnt let me until I deleted the delete code, same problem when i tried to add new admins, so I tried to ask for help in the course with no success and searched for new solutions in the other students problems, but most of them where as lost as I am. Could you please help me fix it?
pd. I'm beyond refound, I'm in the video 457/500 and more time than a month have passed, so I cant ask for it even if I want it.
Here is the model:
<?php
include_once 'funciones/funciones.php';
$usuario=$_POST['usuario'];
$nombre=$_POST['nombre'];
$password=$_POST['password'];
$id_registro =$_POST['id_registro'];
if($_POST['registro'] == 'nuevo') {
$opciones=array(
'cost'=>12
);
$password_hashed=password_hash($password, PASSWORD_BCRYPT, $opciones);
try {
$stmt=$conn->prepare("INSERT INTO admins(usuario, nombre, password) VALUES (?,?,?)");
$stmt->bind_param("sss", $usuario, $nombre, $password_hashed);
$stmt->execute();
$id_registro=$stmt->insert_id;
if ($id_registro > 0) {
$respuesta=array(
'respuesta'=>'exito',
'id_admin'=>$id_registro
);
} else {
$respuesta=array(
'respuesta'=>'error',
);
}
$stmt->close();
$conn->close();
} catch (\Exception $e) {
echo "Error: " . $e->getMessage();
}
die(json_encode($respuesta));
}
if($_POST['registro'] == 'actualizar') {
try {
if (empty($_POST['password']) ) {
$stmt = $conn->prepare("UPDATE admins SET usuario = ?, nombre = ?, editado = NOW() WHERE id_admin = ? ");
$stmt->bind_param("ssi", $usuario, $nombre, $id_registro);
} else {
$opciones = array(
'cost' => 12
);
$hash_password = password_hash($password, PASSWORD_BCRYPT, $opciones );
$stmt = $conn->prepare('UPDATE admins SET usuario = ?, nombre = ?, password = ?, editado = NOW() WHERE id_admin = ? ');
$stmt->bind_param("sssi", $usuario, $nombre, $hash_password, $id_registro);
}
$stmt->execute();
if ($stmt->affected_rows) {
$respuesta = array(
'respuesta' => 'exito',
'id_actualizado' => $stmt->insert_id
);
}else {
$respuesta = array(
'respuesta' => 'error'
);
}
$stmt->close();
$conn->close();
} catch (\Exception $e) {
$respuesta = array(
'respuesta' => $e->getMessage()
);
}
die(json_encode($respuesta));
}
if($_POST['registro'] == 'eliminar') {
//die(json_encode($_POST));
$id_borrar = $_POST['id'];
try {
$stmt = $conn->prepare('DELETE FROM admins WHERE id_admin = ? ');
$stmt->bind_param('i', $id_borrar);
$stmt->execute();
if($stmt->affected_rows){
$respuesta = array(
'respuesta' => 'correcto',
'id_eliminado' => $id_borrar
);
} else {
$respuesta = array(
'respuesta' => 'cancel'
);
}
} catch (\Exception $e) {
$respuesta = array{
'respuesta' => $e->getMessage();
};
}
die(json_encode($respuesta));
}
if(isset($_POST['login-admin'])) {
$usuario=$_POST['usuario'];
$password=$_POST['password'];
//die(json_encode($_POST));
try {
include_once 'funciones/funciones.php';
$stmt=$conn->prepare("SELECT * FROM admins WHERE usuario = ?;");
$stmt->bind_param("s", $usuario);
$stmt->execute();
$stmt->bind_result($id_admin, $usuario_admin, $nombre_admin, $password_admin, $editado);
if ($stmt->affected_rows) {
$existe=$stmt->fetch();
if ($existe) {
if(password_verify($password, $password_admin)){
session_start();
$_SESSION['usuario']=$usuario_admin;
$_SESSION['nombre']=$nombre_admin;
$respuesta=array(
'respuesta'=>'exitoso',
'usuario'=>$nombre_admin
);
} else {
$respuesta=array(
'respuesta'=>'error'
);
}
} else {
$respuesta=array(
'respuesta'=>'error'
);
}
}
$stmt->close();
$conn->close();
} catch(Exception $e){
echo "Error: " . $e->getMessage();
}
die(json_encode($respuesta));
}
?>
Here is the admin-ajax:
$(document).ready(function(){
$('#guardar-registro').on('submit', function (e) {
e.preventDefault();
var datos = $(this).serializeArray();
$.ajax({
type: $(this).attr('method'),
data: datos,
url: $(this).attr('action'),
dataType: 'json',
success: function(data){
console.log(data);
var resultado = data;
if(resultado.respuesta == 'exito'){
Swal.fire(
'Correcto!',
'El administrador se creo correctamente!',
'success'
)
}else {
Swal.fire(
'Error!',
'Hubo un error!',
'Error'
)
}
}
})
});
// eliminar registros
$('.borrar-registro').on('click', function (e) {
e.preventDefault();
let id = $(this).attr('data-id');
let tipo = $(this).attr('data-tipo');
Swal.fire({
title: '¿Estás seguro?',
text: "Un registro eliminado no se puede recuperar",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, Eliminar!',
cancelButtonText: 'Cancelar'
}).then((result) => {
if (result.value) {
$.ajax({
type: 'post',
data: {
'id': id,
'registro': 'eliminar'
},
url: 'modelo-' + tipo + '.php',
success: function (data) {
var resultado = JSON.parse(data);
if (resultado.respuesta == 'correcto') {
Swal.fire(
'Eliminado!',
'Se eliminó el registro de la dase de datos.',
'success'
)
jQuery('[data-id="' + resultado.id_eliminado + '"]').parents('tr').remove();
}
}
})
} else if (result.dismiss === 'cancel') {
Swal.fire(
'Cancelado',
'No se eliminó el registro',
'error'
)
}
})
});
$('#login-admin').on('submit', function (e) {
e.preventDefault();
var datos = $(this).serializeArray();
$.ajax({
type: $(this).attr('method'),
data: datos,
url: $(this).attr('action'),
dataType: 'json',
success: function(data) {
console.log(data);
var resultado = data;
if(resultado.respuesta == 'exitoso'){
Swal.fire(
'Login Correcto!',
'Bienvenido '+resultado.usuario+' !!',
'success'
)
setTimeout(function(){
window.location.href = 'admin-area.php';
}, 2000);
}else {
Swal.fire(
'Error!',
'Usuario o Password Incorrecto! !',
'Error'
)
}
}
})
});
});
pdd. Im sorry, I know I'm bad at this, but thank you for your time.
Edit 1: I can log in and add new admins again if I delete the "eliminar" (delete) part added again, that was an error in my pc I gess, but still can't do it with the delete part.
The code is working now, this is how it end up and thanks to @Swati for the help and time given.
modelo admin:
if ($_POST['registro'] == 'eliminar') {
$id_borrar = $_POST['id'];
try {
$stmt = $conn->prepare('DELETE FROM admins WHERE id_admin = ?');
$stmt->bind_param('i', $id_borrar);
$stmt->execute();
if($stmt->affected_rows){
$respuesta = array(
'respuesta' => 'exito',
'id_eliminado' => $id_borrar
);
}else {
$respuesta = array(
'respuesta' => 'error'
);
}
} catch (Exception $e) {
$respuesta = array(
'respuesta' => $e->getMessage()
);
}
die(json_encode($respuesta));
}
admin ajax:
$('.borrar_registro').on('click', function(e) {
e.preventDefault();
let id = $(this).attr('data-id');
let tipo = $(this).attr('data-tipo');
Swal.fire({
title: '¿Estás Seguro?',
text: "Un usuario eliminado no se puede recuperar",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, Eliminar',
cancelButtonText: 'Cancelar'
}).then((result) => {
if (result.value) {
$.ajax({
type: 'post',
data: {
'id': id,
'registro': 'eliminar'
},
url: 'modelo-' + tipo + '.php',
success: function(data) {
console.log(data);
let resultado = JSON.parse(data);
if (resultado.respuesta === 'exito') {
Swal.fire(
'¡Eliminado!',
'El registro a sido eliminado',
'success'
)
jQuery('[data-id="' + resultado.id_eliminado + '"]').parents('tr').remove();
} else {
Swal.fire(
'¡Error!',
'No se pudo eliminar',
'error'
)}
}
})
} else if (result.dismiss === 'cancel') {
console.log(id);
Swal.fire(
'Cancelado',
'No se eliminó el registro',
'error'
)
}
});
});