-2

I want to make an array from a SQL table, and the page returns "null".

I have tried the following code, which gives me a blank page, I think the problem is in the "while".


$;result = mysqli_query($cnx, "SELECT * FROM matches WHERE pseudo = 'alan'");
while($array = mysqli_fetch_assoc($result));
echo ($array);

I want to echo the data from the database on the page using this method, I want to create an array of the SQL table, to use it in the future.

Shadow
  • 33,525
  • 10
  • 51
  • 64
Alan
  • 1
  • 3
  • 2
    this can't be your real code due to syntax errors. hard to help without **real** code. should check the query actually worked before checking what it returned –  Aug 22 '19 at 23:09
  • [The docs](https://www.php.net/manual/en/mysqli-result.fetch-assoc.php) are pretty clear that `mysqli_fetch_assoc` returns a row and `null` when there are no more rows. What makes you think overwriting a variable will make it into an array and not just the last thing `mysqli_fetch_assoc` returned (`null`)? – gre_gor Aug 22 '19 at 23:13

1 Answers1

1

Three main problems.

  1. Unless you've made a typo in the question here, you're initially getting a blank page because your code has a syntax error.
    $;result will cause a parse error, and if you don't have error reporting turned on that will result in a blank page. None of the code will be executed at all if there's a parse error. While you're dealing with error reporting, make sure you can see mysqli errors as well.

  2. If you fix that syntax error, you'll still get a blank page. The semicolon at the end of the while loop means that the loop does not contain any statements. It will fetch all the query results without doing anything to any of them, and when it's finished, $array will be the last fetched value (null). echo null; doesn't print anything.

    You should use brackets to make sure any of the following statements you want to be executed in the loop are grouped together. If you want to put all the rows from the query into one array, you can do it like this:

    while ($row = mysqli_fetch_assoc($result)) {
        $all_the_rows[] = $row;
    }
    
  3. You can't echo an array.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80