我有一个表单,它将信息发布到一个表,并使用第一个表中的外键将图片发布到第二个表,两次插入都是成功的,但我的重定向语句不是。。。
这是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)
这意味着newImage
的返回值需要评估为true。但是,当函数返回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();
return true;
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
}