javascript - Saving php data from mysql_fetch_array as script variables
been trying to save my data from my while loop to script variables but no success. Did an example if how I want to save my php data to script variables. This doesn't work for me. Anyone have any idea? Don't want to save all data manually. Very greatful for answers! Ask if you don't understand :) Right now it only saves the last variable in the row2.
$id = 0;
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
$id2 = 0;
$sql = mysql_query("select * from table where id = '".$data."'");
while($row2 = mysql_fetch_array($sql)){
$id2 = $id2 + 1;
$var = $row2['var']; //lets say this one is HT123
}
$savethis = "var data" . $id . "_" . $id2 . " = '" . $var . "';";
}
echo "<script>";
echo $savethis;
//I want it to equal like "var data1_1 = 'HT123';
//And then do this for each row, so:
//var data1_2 = 'HW132';
//var data1_3 = 'PQ542';
//var data2_1 = 'SA210';
//Etc
echo "</script>";
Answer
Solution:
I'd really recommend using PDO as mysql_fetch_array() will be deprecated in the near future.
Having that in mind, if you could do it with PDO (here is where you can learn to set up a PDO connection), I think this might work (just working off the top of my head as I don't have your data to work with:
Again, that is just a rough idea and might have kinks in it. But that should give you nested arrays keyed by the ids. So it might look (hopefully) like this:
You can have them interact by using AJAX to send the request to your PHP file, then you can expect the JSON array as the response.
Answer
Solution:
you can use json_encode to do the dirt work for you!
this will encode whatever you have ti json format(no matter array or object or variable)
Answer
Solution:
You need to place
$var
in Apostroff. Without it you will have error in js code.Answer
Solution:
done this stuff before. just gonna give you a rough idea on how will this work.
add this before "while" then increment after while loop:
set $var to array and count its value after while loop:
code will then look like this:
loop "script":
AND THIS IS HOW YOUR COMPLETE CODE WILL LOOK LIKE:
core solution revolves around array. hope this helps :)