r/PHPhelp • • Oct 09 '21

Solved Php array values are repeating

Hi Guys,

I am using postman to see the response of my php code and the first value of my array is repeating itself --- not sure why please have a look into my code:

<?php

include 'connection.php';
$con = mysqli_connect($servername,$username,$password,$database);

$allStories = "SELECT * FROM stories ORDER BY rand()";
$loadStories = mysqli_query($con,$allStories);

if($loadStories->num_rows > 0){
while($row[] = $loadStories->fetch_assoc()){
$item = $row;
$json = json_encode($item);
echo $json;
#print_r($json);
}
}
else{
echo json_encode('Content not loaded...');
mysqli_error($con);
exit();
}
mysqli_close($con);
 
?>

POSTMAN RESPONSE::

[{"sid":"1","story_title":"First Story","story_body":"<p>This is a sample story body text
	<\/p>","story_image":"https:\/\/img.freepik.com\/free-photo\/eurasian-wolf-white-winter-habitat-beautiful-winter-forest_475641-692.jpg?size=626&ext=jpg","genere_title":"Self
		help","upload_date":"2021-10-03"}][{"sid":"1","story_title":"First Story","story_body":"<p>This is a sample
		story body text
		<\/p>","story_image":"https:\/\/img.freepik.com\/free-photo\/eurasian-wolf-white-winter-habitat-beautiful-winter-forest_475641-692.jpg?size=626&ext=jpg","genere_title":"Self
			help","upload_date":"2021-10-03"},{"sid":"2","story_title":"Second Story","story_body":"<p>This is a second
			story body text.
			<\/p>","story_image":"https:\/\/img.freepik.com\/free-photo\/eurasian-wolf-white-winter-habitat-beautiful-winter-forest_475641-692.jpg?size=626&ext=jpg","genere_title":"Self
				help","upload_date":"2021-10-03"}]

Please help me resolve this issue

I only have 2 sample data in mysql database

8 Upvotes

6 comments sorted by

View all comments

Show parent comments

3

u/SNES-Chalmers89 Oct 09 '21

Then you will need to json_encode after the whole loop

2

u/linux_terminal07 Oct 09 '21

Can you help me with the code? as in my code I have already used json_encode inside while loop

4

u/SNES-Chalmers89 Oct 09 '21

Try:

$items = [];
while($row = $loadStories->fetch_assoc()){
    $items[] = $row;
}
echo json_encode($tems);

3

u/linux_terminal07 Oct 09 '21

Thanks a lot mate it worked!! Thank you very much... appreciate your time :)