lee1963 Posted December 3, 2010 Share Posted December 3, 2010 help required for noobie(no hair left) all i want to be able to do is use the individual elements of the array in javascript eg companyname or companyimage but just getting my head in my hand. mysql_select_db("herefordinfo") or die(mysql_error()); echo "Connected to Database"; $dbQuery = 'SELECT * FROM companies'; $dbResult = mysql_query($dbQuery) or die ("Could not read data because " . mysql_error()); $RowCount = mysql_numrows($dbResult); while ($pubs = mysql_fetch_assoc($dbResult)) { $array[] = "{ {$pubs['id']}, {$pubs['companyname']}, {$pubs['companyinfo']}, {$pubs['companyimage']} }"; } echo 'var pub = [' . implode(', ', $array) . '];'; // this ?> <html> <head> <script type="text/javascript"> var jsArray = <?php echo json_encode($array); ?>; document.write(jsArray); //this </script> </head> <boby></body> </html> both php and javescritp output the results below { 1, lichfield vaults, 10 church street hereford , lich.jpg },{ 2, Black Lion, bridge street, blacklion.jpg },{ 3, Saracens Head, st martins street, saracens.jpg } Link to comment https://forums.phpfreaks.com/topic/220560-mysql-php-and-json/ Share on other sites More sharing options...
kenrbnsn Posted December 3, 2010 Share Posted December 3, 2010 You're over-thinking this, try something like this: <?php $dbQuery = 'SELECT * FROM companies'; $dbResult = mysql_query($dbQuery) or die ("Could not read data because " . mysql_error()); $RowCount = mysql_numrows($dbResult); while ($pubs = mysql_fetch_assoc($dbResult)) { $array[] = array('id'=>$pubs['id'],'companyname'=>$pubs['companyname'],'companyinfo'=>$pubs['companyinfo'],companyimage=>$pubs['companyimage']); } echo '<pre>' . print_r($array,true) . '</pre>'; echo '<pre>' . json_encode($array) . '</pre>'; ?> <html> <head> <script type="text/javascript"> var jsArray = <?php echo json_encode($array); ?>; document.write(jsArray[0].companyname); //this </script> </head> <boby></body> </html> Ken Link to comment https://forums.phpfreaks.com/topic/220560-mysql-php-and-json/#findComment-1142702 Share on other sites More sharing options...
lee1963 Posted December 4, 2010 Author Share Posted December 4, 2010 firstly thx for response , your right i do have a tendancy to overly complicate things think its because im still new to this. but slowly getting the hang of it. could you give me some snippet of code that will help me with javascript side. think then i can get on , thx in advance Link to comment https://forums.phpfreaks.com/topic/220560-mysql-php-and-json/#findComment-1142841 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.