PHP/MySQL——不知何故,我多次执行了insert查询

PHP/MySQL——不知何故,我多次执行了insert查询,php,mysql,Php,Mysql,这是我的密码: <?php function ConnectWithMySQLiDatabase() { global $dbhost, $dbuser, $dbpass, $database, $HTTP_SERVER_VARS; $conn = new mysqli($dbhost, $dbuser, $dbpass, $database); // Check connection if (mysqli_connect_errno())

这是我的密码:

<?php

function ConnectWithMySQLiDatabase() {

     global $dbhost, $dbuser, $dbpass, $database, $HTTP_SERVER_VARS;

    $conn = new mysqli($dbhost, $dbuser, $dbpass, $database);
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }


    $conn->set_charset("utf8");

    return $conn;

}

function ConnectWithMySQLDatabase() {

    global $dbhost, $dbuser, $dbpass, $database, $HTTP_SERVER_VARS;

        $conres=mysql_connect($dbhost, $dbuser, $dbpass);

    if (!$conres)
    {
      switch (mysql_errno())
      {
        case 1040:
        case 2002:
            if ($HTTP_SERVER_VARS[REQUEST_METHOD] == "GET")
                die("<html><head><meta http-equiv=refresh content=\"20 $HTTP_SERVER_VARS[REQUEST_URI]\"></head><body><table border=0 width=100% height=100%><tr><td><h3 align=center>".ERR_SERVER_LOAD."</h3></td></tr></table></body></html>");
            else
                die(ERR_CANT_CONNECT);
        default:
            die("[" . mysql_errno() . "] dbconn: mysql_connect: " . mysql_error());
      }
    }
    mysql_select_db($database)
        or die(ERR_CANT_OPEN_DB." $database - ".mysql_error());

    mysql_set_charset('utf8',$conres);  

}
ConnectWithMySQLDatabase();
$conn = ConnectWithMySQLiDatabase();

$today = date("Y-m-d");


$result=mysql_query("SELECT * FROM `Updates` WHERE `Date`='$today'");

$count=mysql_num_rows($result);

$vs = $conn->query("SELECT * FROM `Updates` WHERE `Date`='$today'");



$vrowis = $vs->fetch_assoc();

$Updates = $vrowis['Updates'];  


if($count == 0){
    mysql_query("INSERT INTO `Updates` (`id`, `Date`, `Updates`) VALUES (NULL, '$today', '1')");
}

if($Updates == 1){
    mysql_query("UPDATE `Updates` SET `Updates`='2' WHERE `Date`='$today'");
    mysql_query("TRUNCATE TABLE products;");
    mysql_query("TRUNCATE TABLE ProductSizes;");
}

if($Updates == 2){


$v = $conn->query("SELECT * FROM `categories` WHERE `Link`!='' AND `LastUpdated`!='$today'");



while ($vrowi = $v->fetch_assoc()) {

$url = $vrowi['Link'];  
$Cat = $vrowi['id'];

if($Cat!=""){
$conn->query("UPDATE `categories` SET `LastUpdated`=NOW() WHERE `id`='$Cat'");


    $curl = curl_init();
    curl_setopt($curl, CURLOPT_COOKIE, "ChosenSite=www; SportsDirect_AnonymousUserCurrency=GBP; language=en-GB");
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSLVERSION, 3);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
    curl_setopt($curl, CURLOPT_VERBOSE, true);
    $str = curl_exec($curl);  
    curl_close($curl);  


    libxml_use_internal_errors(true); 
    $doc = new DOMDocument();
    $doc->loadHTML($str);

    $xpath = new DOMXpath($doc);

$n  = $xpath->query('//div[@class="s-producttext-top-wrapper"]');
$l  = $xpath->query('//div[@class="s-producttext-top-wrapper"]/a');
$p  = $xpath->query('//div[@class="s-largered"]');
$im  = $xpath->query('//a[@class="ProductImageList"]');
$sd  = $xpath->query('//span[@class="productdescriptionbrand"]');
$sds  = $xpath->query('//div[@class="s-producttext-top-wrapper"]/a');

$nl = $xpath->query('//a[@class="swipeNumberClick"][last()]');

if ($nl->length) {
$NextLink  = $nl->item(0)->getAttribute("data-dcp");
} else {
    $NextLink = "";
}

$item = 0;
$i = 1;
$Number = 0;
$Number1 = 0;
foreach ($n as $entry) {

    $Name      = trim($entry->nodeValue);
    $Link      = $l->item($item)->getAttribute("href");
    $SDCodes       = $sds->item($item)->getAttribute("href");
    $SDCodes  = substr($SDCodes, strpos($SDCodes, "?colcode=") + 9);
    $SDCode        = $sd->item($item)->nodeValue;
    $ImageCode = substr($Link, strpos($Link, "?colcode=") + 9);
    $Image = 'http://images.sportsdirect.com/images/products/'.$ImageCode.'_l.jpg'; 
    $Price     = trim($p->item($item)->nodeValue);
    $Find = array('£','From','/5','  ','<br/>');
    $Replace   = array('','','','','');

    $FindName = array('/n','<br/>','<br>');
    $ReplaceName   = array('','','');       

    $Price = str_replace($Find, $Replace, $Price);
    $Rating = str_replace($Find, $Replace, $Rating);
    $Name = str_replace($FindName, $ReplaceName, $Name);

    $Name = preg_replace('!\s+!', ' ', $Name);
    $item++;

    // Start fetching info from the product itself
    if($Link != "{{PrdUrl}}"){
    $urlIn = "http://www.sportsdirect.com/$Link";
    $curlIn = curl_init();
    curl_setopt($curlIn, CURLOPT_COOKIE, "ChosenSite=www; SportsDirect_AnonymousUserCurrency=GBP; language=en-GB");
    curl_setopt($curlIn, CURLOPT_URL, $urlIn);
    curl_setopt($curlIn, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curlIn, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curlIn, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curlIn, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curlIn, CURLOPT_SSLVERSION, 3);
    curl_setopt($curlIn, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($curlIn, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
    curl_setopt($curlIn, CURLOPT_VERBOSE, true);
    $strIn = curl_exec($curlIn);  
    curl_close($curl);  


    libxml_use_internal_errors(true); 
    $docIn = new DOMDocument();
    $docIn->loadHTML($strIn);

    $xpathIn = new DOMXpath($docIn);
    $DataVariants = $xpathIn->query('//span[@class="ImgButWrap"]/@data-variants')->item(0)->nodeValue;

    $jsonStart = strpos($DataVariants, '[');
    $jsonEnd = strrpos($DataVariants, ']');

    $collections = json_decode(substr($DataVariants, $jsonStart, $jsonEnd - $jsonStart + 1));   

    foreach ($collections as $itemr) {
        $ColVarId = $itemr->ColVarId;           

        if ($ColVarId == $SDCodes){ 
        foreach ($itemr->SizeVariants as $sizer) {
            $SellPrice = $sizer->ProdSizePrices->RefPrice;  
            $healthy2 = array('£',' ','Â');
            $yummy2   = array('','','');
            $PriceOld = str_replace($healthy2, $yummy2, $SellPrice);

        }   
    }       

    }
    $GetPercent = $Price / $PriceOld;
    $PercentDiscount = $GetPercent * 100;
    $PercentDiscount = 100 - $PercentDiscount;
    if($PercentDiscount == 100){
        $PercentDiscount = 0;
    }
    $PercentDiscount = number_format($PercentDiscount, 2, '.', '');

    $options = $xpathIn->query('//ul[@id="dnn_ctr103511_ViewTemplate_ctl00_ctl14_ulSizes"]/li');

    $results1=mysql_query("SELECT * FROM `products` WHERE `Title`='$Name' AND `Price`='$Price'");

    $count1=mysql_num_rows($results1);  

        foreach ($options as $Sentry) {

            $Size      = trim($Sentry->getAttribute("title"));
            if (strpos($Size,'is out of stock') !== false) {
                $Size = "";
            }
            $Sizes = $Size;
            if($Sizes != ""){
                $healthy3 = array('Click to select ');
                $yummy3   = array('',);
                $Sizes = str_replace($healthy3, $yummy3, $Sizes);
            if($count1 == 0){               
                $conn->query("INSERT INTO `ProductSizes` (`id`, `Size`, `Product`, `Category`,`Brand`) VALUES (NULL, '$Sizes', '$SDCodes', '$Cat','$SDCode')");
            }
            }

        }       

    }       
    //      



    if($Link != "{{PrdUrl}}"){
    preg_match('/-(\d+)\?/', $Link, $result);
    $ProductCode = $result[1];          
    $Number++;


    if($count1 == 0){
            $conn->query("INSERT INTO `products` (`id`, `Title`, `Description`, `Price`,`PriceOld`,`PercentDiscount`,`SDProductCode`,`Brand`,`Rating`, `Image`, `Link`, `Stock`, `ProductCode`, `Category`, `Hot`, `New`, `Type`, `Created`) VALUES 
                                        (NULL, '$Name', '', '$Price','$PriceOld','$PercentDiscount','$SDCodes','$SDCode','$Rating', '$Image', '$Link', '1', '$ProductCode', '$Cat', '0', '0', '1', NOW());");
    }
    mysql_close();

    }
$i++;
if($NextLink != "") {
if($i <= $NextLink){
$url1 = "$url?dcp=$i";

    $curl1 = curl_init();
    curl_setopt($curl1, CURLOPT_COOKIE, "ChosenSite=www; SportsDirect_AnonymousUserCurrency=GBP; language=en-GB");
    curl_setopt($curl1, CURLOPT_URL, $url1);
    curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl1, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl1, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl1, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl1, CURLOPT_SSLVERSION, 3);
    curl_setopt($curl1, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($curl1, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
    curl_setopt($curl1, CURLOPT_VERBOSE, true);
    $str1 = curl_exec($curl1);  
    curl_close($curl1);  


    libxml_use_internal_errors(true); 
    $doc1 = new DOMDocument();
    $doc1->loadHTML($str1);

    $xpath1 = new DOMXpath($doc1);

$n1  = $xpath1->query('//div[@class="s-producttext-top-wrapper"]');
$l1  = $xpath1->query('//div[@class="s-producttext-top-wrapper"]/a');
$p1  = $xpath1->query('//div[@class="s-largered"]');
$pold1  = $xpath1->query('//div[@class="RefandPrice"]/span');
$im1 = $xpath1->query('//u[@id="productlistcontainer"]');
$nl1 = $xpath1->query('//a[@class="swipeNumberClick"][last()]');
$sd1  = $xpath1->query('//span[@class="productdescriptionbrand"]');
$sds1  = $xpath1->query('//div[@class="s-producttext-top-wrapper"]/a');



$item1 = 0;
    foreach ($n1 as $entry1) {

        $Name1     = trim($entry1->nodeValue);
        $Link1     = $l1->item($item1)->getAttribute("href");
        $SDCode1       = $sd1->item($item1)->nodeValue;
        $SDCodes1      = $sds1->item($item1)->getAttribute("href");
        $SDCodes1      = substr($SDCodes1, strpos($SDCodes1, "?colcode=") + 9);
        $ImageCode1 = substr($Link1, strpos($Link1, "?colcode=") + 9);
        $Image1 = 'http://images.sportsdirect.com/images/products/'.$ImageCode1.'_l.jpg';       
        $Price1    = trim($p1->item($item1)->nodeValue);
        $PriceOld1     = trim($pold1->item($item1)->nodeValue);
        $Find1 = array('£','From','/5','  ','<br/>');
        $Replace1   = array('','','','','');

        $Price1 = str_replace($Find1, $Replace1, $Price1);
        $PriceOld1 = str_replace($Find1, $Replace1, $PriceOld1);
        $Rating1 = str_replace($Find1, $Replace1, $Rating1);

        $FindName1 = array('/n','<br/>','<br>');
        $ReplaceName1   = array('','','');
        $Name1 = str_replace($FindName1, $ReplaceName1, $Name1);
        $Name1 = preg_replace('!\s+!', ' ', $Name1);

        //
        if($Link1 != "{{PrdUrl}}"){
        $urlIn1 = "http://www.sportsdirect.com/$Link1";
        $curlIn1 = curl_init();
        curl_setopt($curlIn1, CURLOPT_COOKIE, "ChosenSite=www; SportsDirect_AnonymousUserCurrency=GBP; language=en-GB");
        curl_setopt($curlIn1, CURLOPT_URL, $urlIn1);
        curl_setopt($curlIn1, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlIn1, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curlIn1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curlIn1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curlIn1, CURLOPT_SSLVERSION, 3);
        curl_setopt($curlIn1, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($curlIn1, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
        curl_setopt($curlIn1, CURLOPT_VERBOSE, true);
        $strIn1 = curl_exec($curlIn1);  
        curl_close($curlIn1);  


        libxml_use_internal_errors(true); 
        $docIn1 = new DOMDocument();
        $docIn1->loadHTML($strIn1);

        $xpathIn1 = new DOMXpath($docIn1);
        $DataVariants1 = $xpathIn1->query('//span[@class="ImgButWrap"]/@data-variants')->item(0)->nodeValue;

        $jsonStart1 = strpos($DataVariants1, '[');
        $jsonEnd1 = strrpos($DataVariants1, ']');

        $collections1 = json_decode(substr($DataVariants1, $jsonStart1, $jsonEnd1 - $jsonStart1 + 1));  

        foreach ($collections1 as $itemr1) {
            $ColVarId1 = $itemr1->ColVarId;         

            if ($ColVarId1 == $SDCodes1){   
            foreach ($itemr1->SizeVariants as $sizer1) {
                $SellPrice1 = $sizer1->ProdSizePrices->RefPrice;    
                $healthy21 = array('£',' ','Â');
                $yummy21   = array('','','');
                $PriceOld1 = str_replace($healthy21, $yummy21, $SellPrice1);

            }   
        }       

        }
        $GetPercent1 = $Price1 / $PriceOld1;
        $PercentDiscount1 = $GetPercent1 * 100;
        $PercentDiscount1 = 100 - $PercentDiscount1;
        if($PercentDiscount1 == 100){
            $PercentDiscount1 = 0;
        }           
        $PercentDiscount1 = number_format($PercentDiscount1, 2, '.', '');
        $options1 = $xpathIn1->query('//ul[@id="dnn_ctr103511_ViewTemplate_ctl00_ctl14_ulSizes"]/li');

            $result2=mysql_query("SELECT * FROM `products` WHERE `Title`='$Name1' AND `Price`='$Price1'");

            $count2=mysql_num_rows($result2);

            foreach ($options1 as $Sentry1) {

                $Size1     = trim($Sentry1->getAttribute("title"));
                if (strpos($Size1,'is out of stock') !== false) {
                    $Size1 = "";
                }
                $Sizes1 = $Size1;
                if($Sizes1 != ""){
                $healthy31 = array('Click to select ');
                $yummy31   = array('',);
                $Sizes1 = str_replace($healthy31, $yummy31, $Sizes1);
                if($count2 == 0){   
                $conn->query("INSERT INTO `ProductSizes` (`id`, `Size`, `Product`, `Category`,`Brand`) VALUES (NULL, '$Sizes1', '$SDCodes1', '$Cat','$SDCode1')");
                }
                }   
            }                       
        }           
        //          

        $item1++;

        if($Link1 != "{{PrdUrl}}"){
        $Number1++;
        preg_match('/-(\d+)\?/', $Link1, $result1);
        $ProductCode1 = $result1[1];    

    if($count2 == 0){       
        $conn->query("INSERT INTO `products` (`id`, `Title`, `Description`, `Price`,`PriceOld`,`PercentDiscount`,`Brand`,`SDProductCode`,`Rating`, `Image`, `Link`, `Stock`, `ProductCode`, `Category`, `Hot`, `New`, `Type`, `Created`) VALUES 
                                            (NULL, '$Name1', '', '$Price1','$PriceOld1','$PercentDiscount1','$SDCode1','$SDCodes1','$Rating1', '$Image1', '$Link1', '1', '$ProductCode1', '$Cat', '0', '0', '1', NOW());");
    }
    mysql_close();
        }


    }       
    }
}   

}
$FinalNumber = $Number1 + $Number;
$result['ProductsReceived'][0] = $FinalNumber;
echo json_encode($result);
}
}
mysqli_close($conn);
}
?>
此查询:

    if($count1 == 0){
            $conn->query("INSERT INTO `products` (`id`, `Title`, `Description`, `Price`,`PriceOld`,`PercentDiscount`,`SDProductCode`,`Brand`,`Rating`, `Image`, `Link`, `Stock`, `ProductCode`, `Category`, `Hot`, `New`, `Type`, `Created`) VALUES 
                                        (NULL, '$Name', '', '$Price','$PriceOld','$PercentDiscount','$SDCodes','$SDCode','$Rating', '$Image', '$Link', '1', '$ProductCode', '$Cat', '0', '0', '1', NOW());");
    }
    if($count2 == 0){       
        $conn->query("INSERT INTO `products` (`id`, `Title`, `Description`, `Price`,`PriceOld`,`PercentDiscount`,`Brand`,`SDProductCode`,`Rating`, `Image`, `Link`, `Stock`, `ProductCode`, `Category`, `Hot`, `New`, `Type`, `Created`) VALUES 
                                            (NULL, '$Name1', '', '$Price1','$PriceOld1','$PercentDiscount1','$SDCode1','$SDCodes1','$Rating1', '$Image1', '$Link1', '1', '$ProductCode1', '$Cat', '0', '0', '1', NOW());");
    }
正在执行3次。这是我的问题。我希望这些查询只执行一次。我看不出问题出在哪里

你能帮忙吗,给我一些建议


提前谢谢

可能是因为它在while循环中。 创建一个检查以仅运行该while循环一次

$check = 0;

while ($vrowi = $v->fetch_assoc()) {
    if ($check == 0) {
        $check++;
           .......your code
    }
 }
我添加了一个要检查的变量,以便while循环只运行一次


或者您可以只使用if而不是while条件,但请注意,代码中使用的
$HTTP\u SERVER\u VARS
已被弃用。您应该改用
$\u服务器['REQUEST\u METHOD']
。我还注意到,您的代码混合了
mysqli\u xx()
mysql\u xx()
函数。请注意,它们彼此不兼容:您的程序应该一致地使用其中一个。最好始终使用
mysqli
,因为
mysql\u xx()
函数已被弃用。