Skip to content
Advertisement

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, string given in while-loop

I currently have this code but it gives me the error mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, string given on line 22

The code is this:

1   $servername = "localhost";
2   $user = "root";
3   $pass = "";
4   $db = "mafioso";
5
6   $con = mysqli_connect($servername, $user, $pass, $db);
7
8   $cash_utbetaling[0] = 50000000;
9   $cash_utbetaling[1] = 40000000;
10  $cash_utbetaling[2] = 30000000;
11  $cash_utbetaling[3] = 20000000;
12  $cash_utbetaling[4] = 10000000;
13
14  $kuler_utbetaling[0] = 25;
15  $kuler_utbetaling[1] = 20;
16  $kuler_utbetaling[2] = 15;
17  $kuler_utbetaling[3] = 10;
18  $kuler_utbetaling[4] = 5;
19
20  $i = 0;
21  $result = mysqli_query($con, "SELECT * FROM daily_exp ORDER BY exp DESC LIMIT 5");
22  while($row_best = mysqli_fetch_assoc($result)) {
23    
24    $acc_id = $row_best['acc_id'];
25
26    $sql = "SELECT * FROM accounts WHERE ID='".$acc_id."'";
27    $query = mysqli_query($con, $sql) or die (mysqli_error());
28    $row_top5 = mysqli_fetch_assoc($query);
29    
30    $result = "UPDATE accounts SET money = (money + ".$cash_utbetaling[$i]."), 
      bullets = (bullets + ".$kuler_utbetaling[$i].")  WHERE ID = ".$acc_id."";
31    mysqli_query($con, $result) or die("Bad query: $result");
32
33    $i++;
34  }

I can’t seem to find the error, I am running the same code in another file and there is no issues.

Advertisement

Answer

You are overwritting $result

// This is supposed to be
//  a mysqli_result object ----------v-----v
while($row_best = mysqli_fetch_assoc($result)) 
{
    // some code
    // $result is now a string. Next iteration will raises the warning
    $result = "UPDATE accounts SET ...";
}

So you need to give your variables distinct names. Naming a query $result is not the best choice.


Side note.

Your inner queries are vulnerable to SQL injections. One should use prepared statements instead of concatening strings.

In example :

// prepare the query
$query = "SELECT * FROM accounts WHERE ID=?";
if ($stmt = mysqli_prepare($con, $query)) {

    // bind the param
    mysqli_stmt_bind_param($stmt, "s", $acc_id);

    // execute the query
    mysqli_stmt_execute($stmt);

    // get the result. Of course, avoir using the same variable name, again :)
    $result = mysqli_stmt_get_result($stmt);
}

For more informations about prepared statements with mysqli, read the official documentation or the tutorials written by @YourCommonSense

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement