【问题标题】:Fatal error: Uncaught exception 'Exception' with message 'id not supplied'致命错误:未捕获的异常“异常”,消息“未提供”
【发布时间】:2015-01-04 18:38:44
【问题描述】:

完全错误是这样的:致命错误:在第 12 行的 /var/www/html/pdo/Delete.php 中未捕获的异常“异常”和消息“未提供 id”+(!)异常:id 未在 / 中提供var/www/html/pdo/Delete.php 在第 12 行。我正在测试一个页面以调用一个删除函数,该函数删除与我在测试中给出的 id 匹配的行。它有效,它删除了具有该 ID 的行。但是给了我这个警告。这是我的代码:

<?php

    include_once("StudentManager.php");
    //assumption is that the following parameters are passed to this file   
    //$id to be deleted.

    //Tester
    StudentManager::Delete(6); // 6 was the id I deleted.

    extract($_REQUEST); 

    if(!isset($id)){
        throw new Exception("id not supplied");
        echo "Bad";  //It does not get to this.
    } //else {

        //echo StudentManager::Delete($id);

    //}



?>
//Delete(id) and returns the number of rows affected by the delete
    public static function Delete($id){
    $db = StudentManager::getPDOConnection();
    $sql = "DELETE FROM people WHERE id=".$id;

    $di = $db->prepare($sql);     

    $di->execute(array(":id"=>$id));       

    $affected_rows = $di->rowCount();                                    

    echo "<p>$affected_rows rows were Deleted.</p>";
    $db = null;
    return $affected_rows;

} //end of delete

【问题讨论】:

  • 请不要将代码转储到 cmets。编辑我们的原始帖子以添加代码。
  • @Jay Blanchard,谢谢,我删除了我的评论并将其添加到代码中。
  • 你知道预备语句是什么吗?如果是,为什么不使用准备好的语句绑定 id?
  • @N.B.,是的,你是对的,我把它修复得更好,但它仍然给了我例外。它仍然有效,就像从数据库中删除它一样,但它对我来说是致命的。

标签: php mysql pdo


【解决方案1】:
throw new Exception("id not supplied");

此行引发导致您看到的致命错误的异常。

在这种情况下运行:

if(!isset($id)){

很明显,条件匹配,这意味着$id 变量没有设置。

另外,extract($_REQUEST) 是非常糟糕的做法。

简单范围示例:

function foo($a) {
    $a = 5;
    echo $a; //5
}
$a = 42;
echo $a; //42
foo($a); //will echo 5
echo $a; //Still 42. Different $a.

【讨论】:

  • 但是我以为我的检查是看id是不是传进去的,在我的测试中。所以 !isset 应该忽略它,因为它已设置。还是我看错了。
  • 它为什么要检查这样的东西?传递给 isset 的 $id 和传递给函数的 $id 是不同的。了解 PHP 中作用域的工作原理(实际上并没有那么复杂)。
  • 是的,它是范围。我在错误的地方测试我的代码。现在效果很好,我正在其他地方进行测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-26
  • 2016-07-09
  • 1970-01-01
  • 2013-07-07
相关资源
最近更新 更多