I am trying to connect to my database (it is working) and I want to select all data within the table "users". When I am displaying data, while loop with the fetch_assoc() never finishes. I don't understand why this is happening.
Any ideas?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first project!</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php
$servername = "localhost";
$user = "root";
$password = "";
$db = "mydb";
$connection = new mysqli($servername, $user, $password, $db);
if($connection->connect_error) {
die("Es ist ein Fehler aufgetreten: $connection->connect_error");
}
$sql = "SELECT * FROM users";
$result = $connection->query($sql);
$resultArray = $result->fetch_assoc();
if($result->num_rows > 0) {
while($i = $resultArray) {
echo "ID: " . $i["id"] . "<br>Name: " . $i["username"];
}
}
?>
</body>
</html>
If I try this version, it is working - so I don't understand why "my version" isn't. I just tried to adapt it a bit.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first project!</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php
$servername = "localhost";
$user = "root";
$password = "";
$db = "mydb";
$connection = new mysqli($servername, $user, $password, $db);
if($connection->connect_error) {
die("Es ist ein Fehler aufgetreten: $connection->connect_error");
}
$sql = "SELECT * FROM users";
$result = $connection->query($sql);
if($result->num_rows > 0) {
while($i = $result->fetch_assoc()) {
echo "ID: " . $i["id"] . "<br>Name: " . $i["username"];
}
}
?>
</body>
</html>
while($i = $result->fetch_assoc())callsfetch_assocon every loop iteration. Your version only calls it once.