PHP PDO 准备删除.为什么会失败


PHP PDO prepared delete. Why does this fail?

我有一小段代码,我试图通过ajax响应执行。我已经传递了 ID,但由于某种原因我的删除语句失败(不删除记录,因此添加到数组$err(。我确信这是愚蠢的东西,但它现在并没有跳出来。

PHP代码

<?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
    }
?>

更新我已经更改了数据库错误模式,可以显示它。所以它必须与我的数据库的设计方式有关。

致命错误:未捕获的异常"PDOException"与 消息"SQLSTATE[23000]:完整性约束冲突:1451 无法 删除或更新父行:外键约束失败 ( login .thrives、约束thrives_ibfk_1外键 (n_emp ( 参考文献 employees ( ID ((' in /Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/Employees/delete.php:23 堆栈跟踪: #0/Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/Employees/delete.php(23(: PDOStatement->execute(( #1 {main} 扔进 /Applications/XAMPP/xamppfiles/htdocs/jen/maintabs/Employees/delete.php在第 23

$id = is_numeric($_POST['id']);
...
$statement -> BindParam('id', $id, PDO::PARAM_INT);

is_numeric返回一个布尔值$id的值是truefalse,而不是一个数字。

我认为你的问题出在这一行:

$id = is_numeric($_POST['id']);

is_numeric将返回一个布尔值。我认为你想用

intval的东西(int)$_POST['id']。(编辑:@zerkms正确地指出显式强制转换比intval()更好。在这种情况下,它们在功能上是等效的,但强制转换速度更快。