PHP While 循环异常终止:问题诊断与解决方案

PHP While 循环异常终止:问题诊断与解决方案

本文旨在解决php中使用while循环mysql数据库获取数据时,循环只执行一次就停止的问题。通过分析错误信息和代码逻辑,我们将定位问题根源在于变量名冲突,并提供明确的修改方案,确保循环能够正确处理所有数据行。本文还将介绍如何避免类似错误,提升代码的健壮性和可维护性。

在PHP开发中,使用while循环处理从数据库查询返回的结果集是一种常见的操作。然而,开发者有时会遇到循环只执行一次就意外终止的问题,导致部分数据未能被正确处理。本文将深入探讨此类问题的常见原因,并提供详细的解决方案。

问题分析

mysqli_fetch_array()函数抛出“expects parameter 1 to be mysqli_result, String given”的警告时,表明传递给该函数的参数不是预期的MySQL结果集资源,而是一个字符串。这通常意味着在循环内部,原本存储MySQL结果集的变量被意外地覆盖了。

在提供的代码示例中,问题出在以下两段代码:

立即学习PHP免费学习笔记(深入)”;

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

变量$result最初被用于存储mysqli_query()返回的MySQL结果集。但在while循环内部,$result又被用于存储curl_exec()返回的cURL请求结果。这导致在第二次循环开始时,mysqli_fetch_array()接收到的$result不再是MySQL结果集资源,而是一个字符串,从而引发了错误并导致循环终止。

解决方案

解决此问题的关键在于避免变量名冲突。为cURL请求的结果使用一个不同的变量名,例如$curl_result。修改后的代码如下:

$result = mysqli_query($mysqli,$post_query); ... while($row = mysqli_fetch_array($result)){     ...     $curl_result = curl_exec($ch);     ... }

通过将cURL请求的结果存储到$curl_result变量中,可以确保$result变量始终保持对MySQL结果集的引用,从而保证mysqli_fetch_array()函数能够正确地从结果集中获取数据,循环也能正常执行。

代码示例(完整修正版)

<?php ini_set('max_execution_time', '0'); ini_set('max_input_vars', '100000'); ini_set('memory_limit', '-1'); include_once('includes/connection.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'"           ),         ));           $curl_result = curl_exec($curl); // Changed variable name here         if (curl_errno($curl)) {                     echo 'Error:' . curl_error($curl);         }          curl_close($curl);           $json = json_decode($curl_result);         $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);          $curl_result2 = curl_exec($ch); // Changed variable name here          if (curl_errno($ch)) {             echo 'Error:' . curl_error($ch);         }         curl_close($ch);          $json = json_decode($curl_result2, 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;   ?>

注意事项与总结

  1. 变量命名规范: 遵循清晰、一致的变量命名规范,避免使用过于通用的变量名,特别是循环内部。
  2. 作用域理解: 深入理解变量的作用域,避免在不经意间覆盖外部变量。
  3. 调试技巧: 使用var_dump()或print_r()函数打印变量的值,可以帮助快速定位问题。
  4. 错误日志: 开启PHP错误日志,并定期检查,可以及时发现潜在的问题。
  5. 代码审查: 进行代码审查,可以帮助发现潜在的变量名冲突或其他逻辑错误。

通过遵循以上建议,可以有效避免类似问题的发生,提高代码质量和开发效率。在编写复杂的循环逻辑时,务必保持警惕,仔细检查变量的使用情况,确保代码的正确性和健壮性。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享