PDA

View Full Version : mysql data into an array


rndilger
01-25-2005, 06:46 PM
Hi, I'm still quite new to php and mysql and thus have run into the following problem. I would like to read IDs from a database into an array and then pass that array to a javascript function. If I'm thinking correctly, this should be possible as php is server side and javascript client side. Anyways, I've got the following query:

mysql_query("SELECT id FROM hatchery WHERE parent='0' ORDER BY id")

and want to pass the selected ids into an array to be used by a javascript function. Any help would be appreciated!

Thanks

raf
01-25-2005, 09:26 PM
it's not a mysql issue. what server side language are you using? PHP?

rndilger
01-25-2005, 10:12 PM
yes, sorry...in all, i'm using php and javascript

raf
01-25-2005, 10:24 PM
something like

$script = ("<script language=\"JavaScript\">
<!-- Begin array
var arrItems1 = new Array();\n");
$y = '0';
while ($row = mysql_fetch_assoc($result)) {
$script .= ("arrItems1[" .$y . "] = \"" . $row['id'] . "\";\n");
$y ++ ;
}
$script .= ('// End -->
</script>');

rndilger
01-25-2005, 10:57 PM
Thanks for the help!

Just one more question. Is is possible to then pass that array to a function as an argument?

For example...

while(list($id, $parent) = mysql_fetch_row($result))
{
$str.=CreateItem($id, $parent, $arrItems1);
}
return($str);

Function CreateItem($id, $parent, $arrItems1)
{
CODE
}

raf
01-26-2005, 12:37 AM
No.

If you wanna use it as a javascript-array, then it is sent to the browser --> javascript = clientsided. So the PHP is just generating the html-code that you need for your clientside javascript.
if you want to use it as a PHP array, then you need:

$arrItems1 = array();
while ($row = mysql_fetch_assoc($result)) {
$arrItems1[] = $row['id'];
}