Jump to content

Load values from MYSQL using PHP into Javascript arrays


aniket_dj

Recommended Posts

Hi,

 

This thing is freakin me out. I have PHP variables holding the data retrieved from MYSQL and I want to put into Javascript variables. I know

PHP is on server side and there must be someway to transfer data to the client.

 

I am attempting this naive code....which I feel is wrong

 

Can you suggest me the approach for this??

 

<html>
<body>

<?php


mysql_connect("localhost", "root", "********") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());

//echo "Operation successful";

$query = "SELECT * FROM profile";

$result = mysql_query($query) or die(mysql_error());

echo "<script type='text/javascript'>\n";
//echo "document.write('Javascript running.....');\n";
echo "var i=0;";
//echo "document.write('var =' + i);";
echo "</script>"; 


while($row = mysql_fetch_array($result))
{
	echo "<script type='text/javascript'>\n";
	echo "var arr = new Array();";
	echo "arr[0]=$row[0];";
	echo "document.write(arr[0]);\n";
	//echo "document.write('New value of i is' + i);\n";
	echo "</script>"; 



	echo $row[0]." ".$row[1]."<br>";
}

echo "<script type='text/javascript'>\n";
//echo "document.write('Final Value of i is ' + i);\n";
echo "</script>"; 
?>


</body>
</html>	

Link to comment
Share on other sites

All you have to do is escape out of the quotations in your echo statement...

 

while($row = mysql_fetch_array($result))

{

echo "<script type='text/javascript'>\n";

echo "var arr = new Array();";

echo "arr[0]=" . $row[0]; // Right here, you leave javascript and go into PHP to get the value, which is printed into JS

echo "document.write(arr[0]);\n";

//echo "document.write('New value of i is' + i);\n";

echo "</script>";

 

 

echo $row[0]." ".$row[1]."<br>";

}

 

Just do that for the other vars too.

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.