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>	

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.

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.