如果条件成功后 isset 无法正常工作

If isset not working properly after condition is successful

我有一个表格,可以将信息发布到一个 table,将图片发布到第二个 table,使用第一个 table 的外键,两次插入都成功了,但是我的重定向语句不是...

这是 PHP 代码:

if (isset($_POST['btn-save'])) {
        $itemname = $_POST['title'];
        $price = $_POST['price'];
        $description = $_POST['description'];
        $city_city_id = $user->getcityID($_POST['city']);
        $category_category_id = $user->getcategoryID($_POST['category']);
        $user_user_id = $_SESSION['userSession'];
        if ($user->newItem($itemname, $price, $description, $city_city_id, $category_category_id, $user_user_id)) {
            if (isset($_FILES['image'])) {
                $image = file_get_contents($_FILES["image"]["tmp_name"]);
                $item_item_id = $user->lastInsertID();
                if ($user->newImage($image, $item_item_id)) {
                    header("Location: sellitem.php?inserted");
                }
            } else {
                header("Location: sellitem.php?failure");
            }
        }
    }

这两个函数都用到了:

public function newItem($itemname, $price, $description, $city_city_id, $category_category_id, $user_user_id) {
    try {
        $stmt = $this->db->prepare("INSERT INTO item(itemname,description,price,city_city_id,category_category_id,user_user_id) VALUES(:itemname, :description, :price, :city_city_id, :category_category_id, :user_user_id)");
        $stmt->bindparam(":itemname", $itemname);
        $stmt->bindparam(":description", $description);
        $stmt->bindparam(":price", $price);
        $stmt->bindparam(":city_city_id", $city_city_id);
        $stmt->bindparam(":category_category_id", $category_category_id);
        $stmt->bindparam(":user_user_id", $user_user_id);
        $stmt->execute();
        return true;
    } catch (PDOException $e) {
        echo $e->getMessage();
        return false;
    }
}

public function newImage($image, $item_item_id) {
    try {
        $stmt = $this->db->prepare("INSERT INTO picture(image,item_item_id) VALUES(:image, :item_item_id)");
        $stmt->bindparam(":image", $image);
        $stmt->bindparam(":item_item_id", $item_item_id);
        $stmt->execute();
    } catch (PDOException $e) {
        echo $e->getMessage();
        return false;
    }
}

你包括这一行:

if ($user->newImage($image, $item_item_id))

其中 PHP 计算为:

if ($user->newImage($image, $item_item_id) == true)

这意味着 newImagereturn value 需要评估为真。但是,你的函数只是 returning 一个值,以防它 returns false 时出错。编辑函数以在成功案例中也包含一个 return 值:

public function newImage($image, $item_item_id) {
    try {
        $stmt = $this->db->prepare("INSERT INTO picture(image,item_item_id) VALUES(:image, :item_item_id)");
        $stmt->bindparam(":image", $image);
        $stmt->bindparam(":item_item_id", $item_item_id);
        $stmt->execute();
        return true;
    } catch (PDOException $e) {
        echo $e->getMessage();
        return false;
    }
}