2015-12-21 106 views
0

我有一个表单将信息发布到一个表和一张图片到第二个表中,第一个表中有一个外键,两个插入都是成功的,但是我的重定向语句不是...如果条件成功后isset工作不正常

这是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; 
    } 
} 
+0

什么是错误? –

+3

尝试在函数'newImage'中添加'return true'在try条件下..它应该工作.. –

+1

注意:测试'$ _FILES ['image']'是** NOT **是成功上传的有效测试。所有这些会告诉你,如果上传*尝试*。你需要检查'$ _FILES ['image'] ['error']'。另外,你只是假设查询永远不会失败。这不是编码事物的好方法。您需要显式测试返回值或try/catch。 –

回答

1

您加入这一行:

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

的PHP计算结果为:

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

这意味着newImagereturn value需求评估为真。但是,您的函数仅在返回值为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; 
    } 
}