I’ve got a small bit of code that I’m trying to execute via an ajax response. I’ve got the ID passing, but for some reason my delete statement fails(doesn’t delete record, hence add to $err array). I’m sure it is something stupid, but it isn’t jumping out at me right now.
PHP CODE
<?php
define('INCLUDE_CHECK',true);
require '../../connect.php';
require '../../functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
// sets site to require https
echo redirectToHTTPS();
session_name('tzLogin');
session_set_cookie_params(2*7*24*60*60);
session_start();
if (isset($_POST['id']) && $_SESSION['id'] && $_SESSION['permlvl']==3 )
{
$id = is_numeric($_POST['id']);
$err = array();
$query = "DELETE FROM employees WHERE id = :id";
$statement = $db -> prepare($query);
$statement -> BindParam('id', $id, PDO::PARAM_INT);
$result = $statement -> execute();
$statement -> closecursor();
if ($result === true){
}
else{
$err[] = "error";
}
}
//check for error messages
if(!count($err))
{
echo 'success';
}
else{
//on failure, future will include logging either by sending email or writing to a log file
}
?>
UPDATE
I’ve changed the db error mode and can get this to display. So it has to be something with how my database is designed.
Fatal error: Uncaught exception ‘PDOException’ with
message ‘SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot
delete or update a parent row: a foreign key constraint fails
(login.thrives, CONSTRAINTthrives_ibfk_1FOREIGN KEY (n_emp)
REFERENCESemployees(ID))’ in
/Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/Employees/delete.php:23
Stack trace:
#0 /Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/Employees/delete.php(23):
PDOStatement->execute()
#1 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/Employees/delete.php
on line 23
I think your problem is in this line:
is_numericwill return a bool. I think what you want to use something likeintval(int)$_POST['id']instead. (Edit: @zerkms correctly points out that an explicit cast is better thanintval(). In this case they’re equivalent in functionality, but the cast is faster.)