Home > Software engineering >  Very Strange issue with PHP While Loop
Very Strange issue with PHP While Loop

Time:10-24

I am checking and getting data from MYSQL table and if result is more then 0, I am processing it with while loop. Code is below

<?php
ini_set('max_execution_time', '0');
ini_set('max_input_vars', '100000');
ini_set('memory_limit', '-1');
include_once('includes/connection.php');
//include('bapu.php');
date_default_timezone_set('Asia/Kolkata');
$current_time = date("Y-m-d H:i:s", time());
$post_query = "SELECT * FROM tbl_posts LEFT JOIN tbl_users ON tbl_posts.post_user = tbl_users.id WHERE post_status = 1 AND post_time < '$current_time'";
echo $post_query;
echo "<br>";
$result = mysqli_query($mysqli,$post_query);
$row_cnt = mysqli_num_rows($result);
if($row_cnt<1){
    echo "no data";
    exit();
}
$i =0;
while($row = mysqli_fetch_array($result)){
    $i  ;
    $pid = $row['pid'];
    echo  date("Y-m-d H:i:s", time());
    echo "<br>";
    $post_user = $row['post_user'];
    $title = $row['post_title'];
    $language = $row['post_language'];
    $hashtags =$row['post_tags'];
    $genre = $row['post_category'];
    $subGenre = $row['post_sub_category'];
    $post_tags = $row['post_tags'];
    $image = $row['post_image'];
    $dh_user_id = $row['dh_user_id'];
    $login_status = $row['login_status'];
    $login_expiry = $row['login_expiry'];
    $cookie = $row['cookie'];
    $mobile = $row['dh_mobile'];
    
    
    
    if($login_status!=1 || strtotime($login_expiry) <= time()){
        
       
        $q = "UPDATE tbl_users SET login_status=0, login_expiry = '00-00-00 00:00:00'";
        $r = mysqli_query($mysqli,$q);
        //EMAIL TO USER FOR ERROR OF LOGIN
        
    }else{
        
        $dir = "uploads/".$post_user;
    
        
        $output="";
        $variableAry=explode(",",$hashtags); //you have array now
        $total =  count($variableAry);
                                    
        foreach($variableAry as $i=>$var)
               {
                    $start = '{"title":"';
                    $end = '","id":""},';
                        if(($i 1)==$total){
                             $end = '","id":""}';  
                            }
                                                        
                        $output.=$start.$var.$end;
                }
         $hashtags  = $output;

        $userId =$dh_user_id;
        
        $cookie = 'Cookie: '.$cookie;
        
        $img = $dir.'/'.$image;
        
        file_put_contents(time().'.txt',$img);
        
        //:: FIRST STEP :://
        
        $curl = curl_init();
        
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://example.com/api/image?isFile=true',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_SSL_VERIFYHOST=> 0,
          CURLOPT_VERBOSE=> 1,
          CURLOPT_SSL_VERIFYPEER => 0,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => array('imageFile'=> new CURLFILE("$img")),
          CURLOPT_HTTPHEADER => array(
            "'$cookie'"
          ),
        ));
        

        $response = curl_exec($curl);
        if (curl_errno($curl)) {
                    echo 'Error:' . curl_error($curl);
        }
        
        curl_close($curl);
        
        
        $json = json_decode($response);
        $str = explode("#/", $json->fileName)[1];
        $height = $json->height;
        $width = $json->width;
        
        $str = explode("#/", $json->fileName)[1];
        
        $format = explode(".", $json->fileName)[1];
        
        
        $height = $height;
        $width = $width;
        $url =$str;
        $format =$format;
        
        $data = '{"post":{"fields":{"icon":{"height":'.$height.',"width":'.$width.',"url":"'.$url.'","id":"'.$url.'","format":"'.$format.'"},"image":{"height":'.$height.',"width":'.$width.',"url":"'.$url.'","id":"'.$url.'","format":"'.$format.'"},"title":"'.$title.'","hashtags":['.$hashtags.']},"locations":[""],"language":"'.$language.'","type":"IMAGE","tags":{"dhTags":{"genre":["'.$genre.'"],"subGenre":["'.$subGenre.'"]}},"ttl":{"id":"2","name":"Infinite","type":"NORMAL","value":"31536000"},"action":"submit","postId":null,"updatePublishedDate":false},"userId":'.$userId.'}';
        
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_URL, 'https://example.com/api/post/upsert/update');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "$data");
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $headers = array();
        $headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0';
        $headers[] = 'Accept: application/json, text/plain, */*';
        $headers[] = 'Accept-Language: en-US,en;q=0.5';
        $headers[] = 'Content-Type: application/json;charset=utf-8';
        $headers[] = 'Origin: https://dhcreator.dailyhunt.in';
        $headers[] = 'Connection: keep-alive';
        $headers[] = 'Referer: https://example.com/app/post/create?type=IMAGE';
        $headers[] = "$cookie";
        $headers[] = 'Sec-Fetch-Dest: empty';
        $headers[] = 'Sec-Fetch-Mode: cors';
        $headers[] = 'Sec-Fetch-Site: same-origin';
        $headers[] = 'Te: trailers';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);
        
        $json = json_decode($result, true);
        
        $status = $json['data']['success'];
        if($status){
           $q = "UPDATE tbl_posts SET post_status = 0  WHERE pid = $pid";
           $r = mysqli_query($mysqli,$q); 
        }
        echo "OK ".$status;
    
    }
    sleep(10);
    
    
}

echo "I:".$i;


?>

Its working for only one row and not processing other rows, I mean loop stop after first. I am getting warning like below

 Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, string given in /home/myusername/public_html/dh/cron.php on line 19

I have checked and verified below things

1). I have tried echo my query and tried to run the query in phpmyadmin, there was two results. 2) If I remove codes after assigning variables from while loop and try to run, its work fine and processing both rows. 3) I have not any other codes in while loop which can stop loop.

I am trying various methods from last hour and still not able to find any bug, there no any other errors or warnings get generated in error log even I am logging all types error and warnings. Let me know if anyone here can help me for solve the puzzle.

Thanks!

CodePudding user response:

$result = mysqli_query($mysqli,$post_query);
...
while($row = mysqli_fetch_array($result)){

And later in your loop :

$result = curl_exec($ch);

You lose the MySQL $result, you need to use another variable name for your cURL result.

  •  Tags:  
  • php
  • Related