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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.