I am new to PHP. I am trying to read MySQL with this PHP code.
....
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$rows = array();
$return = array();
while($row = mysqli_fetch_array($result)) {
$rows['UserId'] = $row['UserId'];
$rows['Nick'] = $row['Nick'];
$rows['Items'] = $row['Items'];
$rows['Skills'] = $row['Skills'];
...
$rows['LastUpdate'] = $row['LastUpdate'];
array_push($return, $rows);
}
header("Content-type:application/json");
echo json_encode($return);
Soon after runnning this code, it gets into infinite loop. When I deleted the array_push line, it did not go into infinite loop. So I guess that'd be the problem, but I can't find out why.
Is there something wrong with my code? The MySQL database is in Amazon lightsail.
Please help me. Thanks in advance for any comments.
CodePudding user response:
if you want to fetch all rows from database, and get data array of specific fields
<?php
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$filtered = [];
while($row = mysqli_fetch_all($result)) {
$filtered[] = [
'UserId' => $row['UserId'],
'Nick' => $row['Nick'],
'Items' => $row['Items'],
'Items' => $row['Items'],
'Skills' => $row['Skills'],
'Items' => $row['Items'],
'LastUpdate' => $row['LastUpdate'],
];
}
header("Content-type:application/json");
echo json_encode($filtered);
CodePudding user response:
foreach record of your database information you are entering new data to rows array
while($row = mysqli_fetch_array($result)) {
// Logic of you application here
array_push($return, $row);
}
this pushes fetched row into rows array
how ever if you are not modifying database fetched information. you can fetch information as associative array and simply store it in variable. there will be no need for loop and storing in new array
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
header("Content-type:application/json");
echo json_encode($rows);
