Jump to content

Need help with arrays...Create new array from mysql_fetch_array?


galvin

Recommended Posts

I have a mysql table with columns for (id, mainid, text, image).

 

Say I have this simple code that pulls all the data from the MySQL table (whether there are just a few rows, or whether there are 1000 rows)...

<?php
$sql = "SELECT * FROM table
	WHERE id = $id";
	$getdata = mysql_query($sql, $connection);
		if (!$getdata) { 
		die("Database query failed: " . mysql_error());
		} else {
                }


?>

 

What is the proper way to create a new array with ALL of the returned data in it, so that I can use it to display either now, or maybe later too? 

 

Or is it unnecessary to create a new array since that data is already in an array?  (As you can probably tell, I have never used arrays much and I'm finally realizing they are a must-use in coding. So I want to make sure I use them properly)

 

I think creating a new array makes sense, but I'm getting stuck with how to do it and get all the data for all the rows for easy retrieval where necessary.  I assume this is close, but can't bring it home :)

 

<?php
$sql = "SELECT * FROM table
	WHERE id = $id";
	$getdata = mysql_query($sql, $connection);
		if (!$getdata) { 
		die("Database query failed: " . mysql_error());
		} else {
                                $alldata=array();
			while ($data=mysql_fetch_array($getdata)) {
                                ** $alldata=
                                }

                       }
?>

 

See the "**" to see where I am getting stuck.  How do I write this to get all the fields for all the rows into an array?  Can anyone help?

 

To add $data array to the $alldata array, you'd use this within your while loop

$alldata[] = $data;

 

After your loop you can see the data stored within the $alldata array using print_r

echo '<pre>' . print_r($alldata, true) . '</pre>';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.