简体   繁体   中英

mysqli_conn->query… is not giving any results when put inside for loop

I am unable to get result from the "$mysqli_conn->query" statement which is included in a for loop as shown in the code. The reason I am using for-loop is simple and can be judged from the code itself.

$name=$_SESSION["names"];
$size=sizeof($name);
for($i=0; $i<$size; $i++) { 
    //echo $name[$i]; //for testing
    $bname = $name[$i];
    $results = $mysqli_conn->query("SELECT product_name, product_code FROM products_list WHERE product_name='$bname'");
       if ($row = $results->fetch_assoc()) {
          echo $row["product_name"]."<br>";
        }
        else echo "I am Going Wrong way !!</br>";
}

The output I am getting is : "I am Going Wrong way !!" I also checked the contents of $_SESSION["names"]. Everything seems to be correct except the results.

You're simply assuming your query can never fail, which is a very bad thing. You are vulnerable to sql injection attacks . you are also simply assuming that your queries will ALWAYS return a result. if there's no rows available, fetch will return false, which you then treat as "wrong way".

At bare minimum, you should have a structure like this:

for(...) {
    $results = $mysqli_conn->query($sql);
    if (!$results) {
       die($mysqli_conn->error());
    }
    if ($results->num_rows != 0) {
          $row = $results->fetch_assoc();
    } else {
         echo 'no results';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM