Jump to content

Move an array from php to JScript


zeinaK

Recommended Posts

Hello,

 

I am trying to get a list of elements from my Database and I need to save it in a JavaScript array.

Here is what I've been trying to do.

 

                      mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
                                mysql_select_db($dbname) or die(mysql_error());

                                $query="SELECT idCountries, Country_Name FROM countries order by Country_Name ";
                                $result = mysql_query ($query);
                                
                                $x=1;

                                echo "<script type='text/javascript'>";
  					 
                                echo "var SelAry=[];";		                        

				echo "SelAry[0] = ['select', '0'];";

  				while($nt=mysql_fetch_array($result))
  			        {
				        echo "SelAry[$x]=['$nt[idCountries]', '$nt[Country_Name]']; ";
					$x++;
  				}
			        echo "</script>";

 

I am open to any suggestion.

Thank you in advance.

Link to comment
Share on other sites

Here's one way:

 

while($row = mysql_fetch_array($result)) {
   $rows[] = $row;
}
$data = json_encode($rows);
echo "var SelAry = eval('(' + '$data' + ')');";

 

I usually use a fetch_all() function since I need this throughout an application.  Also, the way you have it you are getting an array with twice the data (numerical indexes and associative).  Adjust for your needs:

 

function mysql_fetch_all($result, $type=MYSQL_ASSOC) {
   $data = array();

   while($row = mysql_fetch_array($result, $type)) {
      $data[] = $row;
   }
   return $data;
}

Link to comment
Share on other sites

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.