PHP

Sending MySQL DB data to JavaScript using PHP

Sending MySQL DB data to JS with help of PHP

Steps :
1. MySQL Connection using PHP (below PHP code is saved as connect.php)

<?php
$host = “localhost”;
$user = “root” ;
$password = “”;
$db=”wordpress”;
$con=mysqli_connect($host,$user,$password,$db);
if(!$con){die(“Failed to connect”);}
?>

2. Retrieve DB data to PHP array.

<?php
require_once(“connect.php”);
$sql=”select * from db_table_name”;
$array=array();
$result=mysqli_query($con,$sql);
foreach($result as $row){
$array[]=$row;
}
?>

3) (i) Assign PHP value to JS variable
<script>
var db_data = <?php echo json_encode($array , JSON_PRETTY_PRINT); ?>;
alert(db_data[db_row_index].db_column_name);
//result maybe 0001.
</script>

3) (ii) Assign PHP value to AngularJS variable (More easy one)
<html>
<div ng-app=””>
<div ng-init=”db_data== <?php echo json_encode($array , JSON_PRETTY_PRINT); ?>” >
<select ng-options=”y.db_colum_name for (x,y) in db_data” >
</select> // Create Select box with db data
</div>
</div>
</html>

Tagged , ,

Leave a Reply