-2

my code is below. I can't get data from table. Please help database.php

 $db = mysqli_connect('localhost','root','','filesproject') or die('Error      connecting to MySQL server.');

index.php

 <?php
 include('config/database.php');

 //Step2
 $query = "SELECT * FROM user";
 mysqli_query($db, $query) or die('Error querying database.');

 //Step3
 $result = mysqli_query($db, $query);
 $row = mysqli_fetch_array($result);

 while ($row = mysqli_fetch_array($result)) {
     echo $row['USERNAME'];
 }

 ?>

And nothing happens, just empty screen

Alex Alex
  • 1
  • 3
  • Are you sure that you're actually getting data from `mysqli_fetch_array`? Maybe your user table is empty – cwallenpoole Sep 05 '17 at 22:35
  • `$row = mysqli_fetch_array($result); while ($row = mysqli_fetch_array($result))` that is definitely failing. – Funk Forty Niner Sep 05 '17 at 22:41
  • Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…”)` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. – tadman Sep 05 '17 at 22:59
  • A lot of problems can be detected and resolved by [enabling exceptions in `mysqli`](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) so mistakes aren't easily ignored. – tadman Sep 05 '17 at 22:59

3 Answers3

1

You have both the query and mysqli_fetch_array twice in your code.

When you call the mysqli_fetch_array the second time, the array needs to be reset.

For simplicity, please try and remove this single line (not what's in the while loop) as it's not needed.

$row = mysqli_fetch_array($result);

More information on resetting the pointer in the array can be found here:

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Colin
  • 159
  • 8
0

Just remove either while ($row = mysqli_fetch_array($result)) and $row = mysqli_fetch_array($result).

Mark Dhem
  • 43
  • 11
0

there is to functions. 1- mysqli_fetch_array($result); 2- mysqli_fetch_assoc($result); and codes are like bellow.

while ($row = mysqli_fetch_array($result)) {
     echo $row[0];
     echo $row[1];
     echo $row[2];
}

and in this case

while ($row = mysqli_fetch_array($result)) {
     echo $row['USERNAME'];
     echo $row['NAME'];
     echo $row['LASTNAME'];
}

for case 1: 0, 1 and 2 are the column position in table.

for case 2: USERNAME, NAME and LASTNAME are the name of column in table.

Abdullah
  • 3
  • 1