Need help forming javascript objects from MySQL rows of data. I'm using IE9 and Chrome on Windows-7.
I've managed to get what I believe to be an array (of objects) in Javascript from mySQL data. I can use alerts to see the whole array, as well as one individual object, as in my code.
What I cannot do yet is navigate a particular object's properties (the column values of a particular row in the database).
What I need to do is iterate through myObjects
, and use the property values in each to create some graphics. I also need to be able to retrieve each object's properties at any time going forward as well.
UPDATE: including my php located in head html object:
<?php
//------------------- constants --------------------
$objects = array();
$jsonData = "";
//------------------- database connection ----------
$data_source = 'mysql:host=localhost;dbname=myDB';
$db_user = 'root';
$db_password = 'password';
$conn = new PDO($data_source, $db_user, $db_password,
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT));
//prepare query
$stmt = $conn->prepare("SELECT * FROM tblbranchstatus");
$stmt->execute();
//fetch each row of results
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$rows[] = json_encode($row);
}
?>
var ART = {};
//capture data from database as json string data
ART.strJSON = <? php echo json_encode($rows); ?> ;
//capture json string data as array of javascript objects
//using 'eval' cause I know this data's source and I couldn't get JSON.parse to work
ART.myObjects = eval(ART.strJSON);
ART.branch = ART.myObjects[6];
alert(ART.branch); // this gives me the expected object {"a":"aa", "b":"bb"...}
alert(ART.branch.a); // can't retrieve the property - gives me 'undefined'