MySQL results Repeating

Im trying to put each user in an Array . eg. array1 = (bob , humphry , 7 bonn avenue)
array2 = (dylan, gordie , 8 lannister str)

But the first user is being repeated in the second array??

$sql = “SELECT user.userName ,user.userSurname, user.avatar, user.status FROM user”;

		if($stmt = $mysqli->prepare($sql)){
				$stmt->execute();
				$stmt->bind_result($name,$surname,$avatar,$status);
				
			while($stmt->fetch()){
				$nameArray[]=($name);
				$nameArray[]=($surname);
				$nameArray[]=($avatar);
				$nameArray[]=($status);
				
				$idArray[] = $nameArray;
			}

You are not clearing your $nameArray after each loop so it will continue to add elements with each iteration. At the same time you are adding the entire contents of $nameArray to $idArray with each iteration. So the first time through $nameArray will be (bob,humphry, 7 bonn avenue) and this will be added to $idArray, which is currently empty. The second time through, $nameArray will be (bob,humphry,7 bonn avenue, dylan, gordi, 8 lannister str) and it will add all of this to $idArray, which already contains the first four elements.

There are several ways to prevent this from happening, including just moving the $idArray declaration outside of your while loop. If all you want is a flat array with the results, I would probably do something like:[php] while($stmt->fetch()){
$idArray[] = array($name,$surname,$avatar,$status);
}}[/php]

Let me know if this doesn’t make sense or work for you.

Thanks so much for the reply . After sitting for hours on that simple task i managed to get it working with a mysql_fetch_array();

Your way seems too simple too be true! Can’t believe i didn’t do that!!!

Glad you got it working. I can’t tell you how many times I have coded for hours, only to later come up with a much simpler solution the next day.

jay

Sponsor our Newsletter | Privacy Policy | Terms of Service