/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Adding data from PHP+MySQL to dynamically created array

I am running through a MySQL database using PHP and extracting all of the makes of cars in that database and trying to create a JavaScript array named after each make. Then I am trying to fill each array will all of the models for that make. When I just try to display each Make and Model in an alert box it seems to come up right. And my arrays seem to be getting created but they won’t populate with the models (even though my alert msg shows the loops and everything is working).

[code=php]
while ($row = mysql_fetch_array($result)) {

$i=0;
//Used so each model is added to the array starting at 0 and ++
$make = $row[‘make’];//PHP var used to extract data from MySQL

print(“<script language = ‘javascript’>var $make=new Array();</script>”);
//Create array

$sql1 = “SELECT DISTINCT (model) FROM $table_name WHERE make=’$make’ ORDER BY model”;
//Extract models from particular make

$result1 = @mysql_query($sql1,$connection) or die(mysql_error());

while ($row1 = mysql_fetch_array($result1)) {

$model = $row1[‘model’];
//PHP var used to extract data from MySQL

//print(“<script language = ‘javascript’> alert(‘$make ‘+’$model’+’ $i’);</script>”);
//If uncommented shows correct data in alert msg

print(“<script language = ‘javascript’>$make[$i]=’$model’;</script>”);
//The key, trying to add $model to array named $make at index $i

//print(“<script language = ‘javascript’>myCars[$i]=’$model’+’ $make’;</script>”);
/*If uncommented shows that adding to array works if it is a statically named array instead of dynamically named based on variable*/

$i++;
}[/code]

Haven’t used JavaScript since a college class a couple of years ago and haven’t used it in the real world for even longer. Never with PHP like this. But I am working on this marketing site and need to be able to list products by type according to each brand and as they can be added to a MySQL database it needs to be dynamic. I have the whole thing working by stepping through separate pages using PHP to populate select fields with the data but I want to be able to dynamically add the content to select field using JavaScript so it can all be done on one page and thought that if I could create these arrays on page load then the right information could be selected client side.

Thanks

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@tirnaFeb 10.2011 — I would do all the dynamic product listing server side because some users, although likely very small in number, will have javascript turned off.

If you must use javascript, then this demo code transfers the data from a php array to a javascript array.

$carData simulates your database data with each row in $carData containing the make of a vehicle and its models.

carData is the javascript array receiving the data in $carData. carData is then displayed to the screen using alert(). You should be able to tweak this code to suit your database data.

[code=php]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title></title>
<script type="text/javascript">
var carData = new Array();
<?php
//this array simulates database data
$carData = array(
array('honda', 'honda_model_1', 'honda_model_2', 'honda_model_3'),
array('ford', 'ford_model_1'),
array('holden', 'holden_model_1', 'holden_model_2'));
$row = 0;
$col = 0;
foreach ($carData as $makeArray) {
echo 'carData[' . $row . '] = new Array();';
foreach ($makeArray as $value) {
echo 'carData[' . $row . '][' . $col++ . '] = "' . $value . '";';
}
++$row;
$col = 0;
}
?>
//display the javascript array
var str = '';
for(i=0; i < carData.length; i++){
for(j=0; j < carData[i].length; j++){
str += carData[i][j]+' ';
}
str += "n";
}
alert(str);
</script>
</head>
<body>
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@KorFeb 10.2011 — I would have used a JSON object. Both PHP and JavaScript have json_encoder, json_parser, json_decoder facilities

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/function.json-decode.php

http://www.json.org/js.html

https://github.com/douglascrockford/JSON-js
Copy linkTweet thisAlerts:
@jwiere03authorFeb 10.2011 — Thanks for the help but I have solved the problem on my own.

Remember the use of alert msg boxes showed that we were looping through our data fine and we seemed to actually be creating the right arrays, just weren't populating them. Changed [code=php]"<script language = 'javascript'>$make[$i] = '$model';</script>"[/code]
to
[code=php]"<script language = 'javascript'>x = $make; x[$i] = '$model';</script>"[/code]
And it works, apparently JS doesn't realize that I am telling it to add content $model to array named $make at place $i. But when I create a JS variable named x and tell it that x has a value of $make and then tell it to add $model to array named x at place $i it understands it fine.
×

Success!

Help @jwiere03 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...