Generating a two dimensional array from database (and converting to javascript)

Hi folks,
I’m trying to create a two dimensional javascript array from the contents of an sql database. I need it to take the form:
array[row 0][field 0];
array[row 0][field 1];
array[row 0][field 2];
array[row 1][field 0];
array[row 1][field 1];
etc etc, flexible to accommodate however many rows and fields there are in the database table.

I’ve sussed out how to convert a php array to javascript (easy using json_encode($array)). The problem I’m having is rendering it in the requitred format. I’m pretty new to all this so its’ highly likely that the answer will be obvious and simple but I’ve come up against a brick wall and would appreciate some help.

The relevant code I’ve written so far is as follows:

[php]$result = mysql_query(“SELECT * FROM exampleTable ORDER BY ID”) or die(‘No table found’);
while ($row = mysql_fetch_array($result)){
$array[] = $row;
}

echo ‘var array = ’ .json_encode($array).’;’;[/php]

Which does, admittedly, return the contents of the database table but not in a format that is useful or usable for what I want to do. I was thinking of something along the lines of:

[php]$result = mysql_query(“SELECT * FROM exampleTable ORDER BY ID”) or die(‘No table found’);
$array = array();

for($i=0; $i<=4;$i++){
	for($ii=0; $ii<=4;$ii++){
		$array[] = array();
			$array[$i][$ii] = array($row[$i]$col[$ii]);
	}
}


echo 'var array = ' .json_encode($array).';';[/php]

… but this is leading to all sorts of problems. In short I’m having problems with the syntax around the for loop for generating the array and after many hours trawling the net for clues am no closer to getting it to work. Like I say, any help would be much appreciated.

Many thanks
Stef

I am not familiar with Json much. But, I think it may just need the correct option in the encode command.
There are about 20 options and some can be combined. Look at this page and see if you can decide which
version of the options. There are various comments that might help too.

If this doesn’t help post again and we can set up some further tests. Also, can you post a small sample of what you get from the encode and what you want it to look like so we can compare?

Good luck…

Actually, I should clarify:

Hi folks,
I’m trying to create a two dimensional javascript array from the contents of an sql database.

The original non-database driven array I was working with looked something like this:

var galleries = new Array(); // Order: id, size, date (yyyymmdd), name, description, thumb image, left px, top px, z-index galleriesOriginal[0] = [0, 12,"20111012","Cats","A gallery of beautiful cat pictures","images/catThumb.jpg",480, 230, 42]; galleriesOriginal[1] = [1, 10,"19990703","Dogs","A gallery of beautiful dog pictures","images/dogThumb",580, 230, 100]; galleriesOriginal[2] = [2, 7,"19970401","Marmolsets","A gallery of beautiful marmoset pictures","images/marmosetThumb.jpg", 580, 330, 100]; galleriesOriginal[3] = [3, 1,"20080610","Anvils","A gallery of beautiful anvil pictures","images/anvilThumb.jpg", 380, 430, 100]; galleriesOriginal[4] = [4, 13,"20101212","Xylophones","A gallery of beautiful xylophone pictures","images/xylophoneThumb.jpg", 680, 430, 100];
etc

… and this is the format I’m looking to recreate (staying away from key/value pairs if possible - is this even possible in PHP?)

Thanks again
Stef

Hi ErnieAlex,
Sorry, uploaded the last bit before I saw your reply - not very familiar with json myself but will investigate further - was there supposed to be a link attached to your post? Basically, trying to reproduce something the same as illustrated in last post of mine.
Thanks
Stef

ps - it’s currently generating a lot of stuff like this:

var array = [{“0”:“6”,“ID”:“6”,“1”:“Even More updated”,“galleryTitle”:“Even More updated”,“2”:“Even More updatedEven More updatedEven More updatedEven More updated”,“3”:“0000-00-00”,“galleryDate”:“0000-00-00”,“4”:“industrial_steampunk_background_stock3_by_valerianastock-d4f3ghi.jpg”,“galleryThumbURL”:“industrial_steampunk_background_stock3_by_valerianastock-d4f3ghi.jpg”},{“0”:“7”,“ID”:“7”,“1”:"Cats glorious cats Update ",“galleryTitle”:"Cats glorious cats Update ",“2”:"Cats, cats glorious cats,\r\nNothing quite like them for nobbling rats. ",“galleryDescription”:"Cats, cats glorious cats,\r\nNothing quite like them for nobbling rats. ",“3”:“0000-00-00”,“galleryDate”:“0000-00-00”,“4”:“gears-blueswirl_steampunk3b.png”,“galleryThumbURL”:“gears-blueswirl_steampunk3b.png”},{“0”:“12”,“ID”:“12”,“1”:"Lice glorious lice ",“galleryTitle”:"Lice glorious lice ",“2”:“sdkjsdjhflsfvlkksjnlk jwelkjfwljefljl weudwpodpowedwepodpow”,“galleryDescription”:“sdkjsdjhflsfvlkksjnlk jwelkjfwljefljl weudwpodpowedwepodpow”,“3”:“0000-00-00”,“galleryDate”:“0000-00-00”,“4”:“camera.jpg”,“galleryThumbURL”:“camera.jpg”}];

One more question…

Is this Javascript array going to be large? Is it updated onscreen dynamically or is the page refreshed?

What I am getting at is why not have PHP pull the data and just format it into the array as you wish?
The PHP could loop thru the rows of data and build the array manually creating the array.
echo" var array["
loop rows
echo"[" . $row[1] . “]” . etc…

Or, just use server-side Javascript to access the database…

I guess that’s what I’m trying to do. The array will have between 5 and 15 rows, each row containing information pertaining to a gallery (ie thumbnail, title, description and various other information).

The reason I’m trying to convert it to a javascript array (as opposed to generate the array using php and then working with that) is that I’m using some jquery animation as part of the navigation system and it seems easier to work with a javascript array than a php one (as you’ll probably have guessed, I’m pretty new to all this and may have bitten off a bit more than i can chew here).

I’m going to try the method you suggested. As for server side javascript, a bit beyond my competence at the moment!)

Thanks again for the help
Stef

Actually, I think it would be easier to create the table in PHP and post it as data for the array for use in Javascript. So, let’s recap my idea which I tried, sort of worked…

PHP code near the beginning of the page inside some javascript. Before the data is needed.
This code does your same MySQL access getting the $row same as before.
Instead of playing with the JSon parts, just output the actual SQL data echo’d in Javascript.
This basically creates Javascript to “load” the array however you want it. (See my demo code below)
Since PHP is SERVER-SIDE, the Javascript get executed as soon as the HTML/Java get posted AFTER the PHP.
So, on “pageload”, the array gets built. So, then it is useful thruout the page. Hope that made sense.
TO test this, add this code to your HTML page, load the page in a browser and RIGHT-CLICK and VIEW-SOURCE. You should be able to see the Javascript building the array. So far, I think this will work.


// Just a sample, need a lot of changes to actually work for your data...
<Script>
var myArray = new Array(new Array));   //creates multidimensional array

// Now load this array with your data from database ( eg:  myArray[1][2]= “row2, field3 data”; )
<?PHP

//connect to db as before
$result = mysql_query("SELECT * FROM exampleTable ORDER BY ID") or die('No table found');
$i=0;
while ( $row = mysql_fetch_row($result) ) {            //Fetch row not array , all fields for this row
         for ($j=0; $j<mysql_num_fields($row); $j++)  // Loop thru all fields in row...
               echo "myArray[" . $i . "][" . $j . "]="'" . $row[$i] . "';";  //NOTE Double-Quote,Quote,Double-Quotes
         $i++;
         }
?>

</script>

NOTES on the above: There are single-quotes around the echo’d data and double-quotes around those.
The process loops thru each row of data and loops thru all the fields in each row and creates Javascript
assignments for the data. I would use arrays and myArray[$i]=array($row) but, this way is more clear.
The output fill every cell in the multidimensional array and echos Javascript versions of this. When the page
loads into the browser the code is executed. (Make sure it is early in the HTML.)

Try that and let me know if it works for you…

Thanks Ernie,
Unfortunately it’s throwing up an error: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ‘,’ or ‘;’ in C:\Users\Stef\wamp\www\sam\createJavascriptArray5.php on line 34, line 34 being:

echo “myArray[” . $i . “][” . $j . “]=”’" . $row[$i] . “’;”; //NOTE Double-Quote,Quote,Double-Quotes

Am trying to suss out where the problem lies.

Cheers
Stef

Okay, got that one worked out…

It’s now throwing up numerous instances of:

“Warning: mysql_num_fields() expects parameter 1 to be resource, array given in C:\Users\Stef\wamp\www\sam\createJavascriptArray5.php on line 33

Within the source code where ‘line 33’ is:

[php]while ( $row = mysql_fetch_row($result) ) { //Fetch row not array , all fields for this row[/php]

Stef

Solved…

As with all of these things turned out to be much simpler than i thought it would be.

PHP code as follows:

[php]$row = mysql_fetch_row($result);
$i=0;
while ($row = mysql_fetch_array($result, MYSQL_NUM)){
$myArray[] = $row;
$i++;
};
print_r($myArray);[/php]
This is then turned into a javascript array as follows:

<script> var galleries = (<?php print json_encode($myArray);?>); </script>
and specific rows abnd fields can be accessed with javascript as follows:

document.write(galleries[0][3]);

(where the first digit refers to the row and the second to the field).

Thanks for your help on this.
Cheers
Stef

Actually, didn’t even need the ‘$i’ - refined code is:

[php]$row = mysql_fetch_row($result);
while ($row = mysql_fetch_array($result, MYSQL_NUM)){
$myArray[] = $row;
};
print_r($myArray);[/php]
S

Great! I was out of the area for a day. Came back expecting to help more. I knew there was a better way to do the $i section, but, ran out of time. Very glad you found that solution. It will help me too with a project I am starting…

Congrats!

Tis cool and thanks once again fir your help… next step is to combine two multi dimensional arrays in javascript… hopefully that won’t cause the same level of wailing and gnashing of teeth as this has done :slight_smile:
S

LOL! Stop Wailing and Gnashing… Just think of it this way, a new routine you can use over and over is now in your mind. Opens up lots more possibilities in your projects! I love finding new code ideas and helping others sort theirs out. Keep coding… (I marked this solved…)

Grin… Wailing (or even ‘whaling’) and gnashing has now officially ceased :slight_smile: Have a good one.
S

Sponsor our Newsletter | Privacy Policy | Terms of Service