1

It gives the output from database along with the above error: "Maximum execution time of 30 seconds exceeded" on line 7.

<?php
require_once 'config.php';//content below
$sql = "select *from users";
$selected = $mysqli->query($sql);
$row = "random";
while($row!=="null"){
    $row = $selected->fetch_assoc();
    echo $row['username']; 
}

In config.php:

<?php
DEFINE('DB_server','localhost');
DEFINE('DB_username','root');
DEFINE('DB_password','');
DEFINE('DB_name','demo');
$mysqli = new mysqli(DB_server,DB_username,DB_password,DB_name);
if($mysqli===NULL){
    die("ERROR: Could not connect. " . $mysqli->connect_error);
}
?>
Dharman
  • 21,838
  • 18
  • 57
  • 107
ram singh
  • 11
  • 1

2 Answers2

1

You are creating an infinite loop. $row will never be equal to a string "null", because $row is an array or a string "random".

Two things. First, you should enable error reporting for MySQLi. It should always be switched on. Use mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); before new mysqli.

<?php
DEFINE('DB_server','localhost');
DEFINE('DB_username','root');
DEFINE('DB_password','');
DEFINE('DB_name','demo');

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli(DB_server,DB_username,DB_password,DB_name);
?>

Second, when you want to loop on the results of your query you can simply use foreach.

<?php
require_once 'config.php';//content below
$sql = "select *from users";
$selected = $mysqli->query($sql);
foreach($selected as $row) {
    echo $row['username']; 
}
Dharman
  • 21,838
  • 18
  • 57
  • 107
0

From the documentation for fetch_assoc (https://www.php.net/manual/en/mysqli-result.fetch-assoc.php),

[...]

while ($row = $result->fetch_assoc()) {
    printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}

[...]

That is how you should call it in a loop.

Nic3500
  • 5,007
  • 10
  • 26
  • 33
  • 1
    Please note that the PHP docs are providing very poor code examples when it comes to mysqli usage. It is much better to enable [exception mode](https://stackoverflow.com/a/18457822/1839439) than to display errors using `die()` and using `foreach` loop is usually simpler than `while` loop. – Dharman Oct 02 '19 at 12:04