3

I've got a little bit of a problem when I try to run this code. I receive this error:

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, object given in

My problem is in the while statement on line 32:

$connection = mysqli_connect($host, $username, $password, $db_name);
$sql = 'SELECT * FROM provinsi';
while ($r = mysqli_fetch_array($connection, $sql)) { // line 32
    $id = $r['id'];
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
age saputra
  • 51
  • 1
  • 1
  • 3

3 Answers3

8

mysqli_fetch_array()'s 1st parameter must be a result of a query. What you are doing is you are passing the connection (which doesn't make sense) and the query command itself.

Read the doc here: http://php.net/manual/en/mysqli-result.fetch-array.php

To fix this, execute the query first, then store the result to a variable then later fetch that variable.

$sql = "select * from privinsi";
$result = mysqli_query($connection,$sql);
while($r = mysqli_fetch_array($result))
{
    // your code here
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Lorence Hernandez
  • 1,189
  • 12
  • 23
  • 1
    in second statement, write mysqli instead of myqli see full code: $sql = "select * from privinsi"; $result = mysqli_query($conn, $sql); while($row = mysqli_fetch_array($result)) { – Billu Apr 24 '18 at 06:55
0

You wrote SQL query but you didn't execute it.

$sql = "select * from privinsi";
$results = mysqli_query($connection, $sql);
while($r = mysqli_fetch_array($results){
   //enter your code here
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Davinder Kumar
  • 652
  • 4
  • 17
-1
$sql = "select * from privinsi";
$result = mysqli_query($connection,$sql);
if (!$result) {
    printf("Error: %s\n", mysqli_error($connection));
    exit();
}else{
   while($row = mysqli_fetch_array($result)){
    // your code here
   }
}

This helps you to display your error so you would be able to find out the exact reason a query is not working. This is helpful when you are using conditions or trying to find specific columns in a table. Tired eyes can make you skip the fact that a particular column is not on your current database and other factors that you can casually overlook when writing a query. If your error is not detailed, you would inevitably run around in circles looking for a solution that is not beyond you.

Sammy
  • 37
  • 6