2013-07-14 42 views
0

我在寫一個腳本來將產品從csv文件上傳到我的網站。我一直有一個問題,當我的if($result) echo "hi";確實存在回顯結果時,但如果我把if(!result)if(empty($result)if(!isset(result))將無法​​回顯時沒有結果...在我的productlist.txt代碼列表中有3產品代碼,其中2個在數據庫中,當我有if($ result)時,它會回顯2'hi',但如果我有if(!result)什麼都沒有回聲,那麼它應該回顯1 hi。PHP腳本不能識別缺失的變量

while($data = fgetcsv($handle)) { 

    //Gets products to be added from txt file. 
    $codes = explode("\n", file_get_contents("productlist.txt")); 

    foreach($codes as $code) { 

     if($data[3] == $code) { 

      $name = $data[2]; 
      $model = $data[3]; 
      $description = strip_tags($data[6]); 
      echo $price = round($data[7] + 20 + (0.05 * $data[7])) - 0.05; echo "</br>"; 
      $image = "data/W_Sexy_Lingerie_Series_Lingerie-Supplies/" . $model . ".jpg"; 

      //Check to see if product already exists 
      $query = "SELECT `product_id` FROM `oc_product` WHERE `model`='$model'"; 
      $result = $con->query($query); 

      if(empty($result)) echo "hi"; 

      break; 

      //Insert product information 
      $query = "INSERT INTO `oc_product` (`model`, `quantity`, `image`, `price`, `status`) VALUES 
      ('$model', '5', '$image', '$price', 1)"; 

      if (!$con->query($query)) { 
       echo $con->error; 
      } 

      //Get product ID 
      $query = "SELECT `product_id` FROM `oc_product` WHERE `model`='$model'"; 
      $result = $con->query($query); 

      $rows = $result->fetch_array(); 

      $product_id = $rows[0]; 

      //Insert product category 
      $query = "INSERT INTO `oc_product_to_category` (`product_id`, `category_id`) VALUES ('$product_id', 59)"; 

      if (!$con->query($query)) { 
       echo $con->error; 
      }   

      //Insert product description 
      $query = "INSERT INTO `oc_product_description` (`product_id`, `language_id`, `name`, `description`,";     $query .= " `meta_description`, `meta_keyword`)"; 
      $query .= " VALUES ('$product_id', 1, '$name', '$description', '$description', '$description')"; 

      if (!$con->query($query)) { 
       echo $con->error; 
      }   

     } 

    } 

} 

} 

newProducts($handle,$con); 
+0

查詢()可能返回你一個不同類型的對象,而不是真/假結果。 –

+0

當出現錯誤時,查詢通常返回'null'或'false' – DevZer0

+0

那麼vardump顯示我只返回2個$結果。 – Melbourne2991

回答

0
if($result->num_rows == 0) echo "hi"; 
+0

不起作用,但是'if($ result-> num_rows> 0)echo「hi」;'回聲兩次.. – Melbourne2991

+0

將'else'加到'if'。你確定你的代碼運行查詢3次嗎?也許'如果($ data [3] == $ code)'只有2次(我只是猜測)。 – furas