【问题标题】:PHP script does not recognise absent variablePHP 脚本无法识别缺少的变量
【发布时间】:2013-07-12 07:21:45
【问题描述】:

我正在编写一个小脚本来将产品从 csv 文件上传到我的网站。我一直有一个问题,我的if($result) echo "hi"; 在 $result 存在时会回显,但是如果我输入 if(!result)if(empty($result)if(!isset(result)) 在没有结果时不会回显...在我的列表中productlist.txt 中的代码 我有 3 个产品代码,其中 2 个在数据库中,当我有 if($result) 时,它会回显 2 'hi' 但如果我有 if(!result) 什么都不会回显,什么时候应该是回响 1 hi。

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);

【问题讨论】:

  • query() 可能会返回不同类型的对象,而不是真/假结果。
  • 查询出错时通常返回nullfalse
  • 嗯,一个 var 转储显示只有 2 个 $results 被返回。

标签: php mysql mysqli php-5.4


【解决方案1】:
if( $result->num_rows == 0 ) echo "hi";

【讨论】:

  • else 添加到if。您确定您的代码运行查询 3 次吗?也许 `if($data[3] == $code)` 只有 2 次为真(我只是猜测)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
相关资源
最近更新 更多