AngularJS + PHP + MySQL to display data from database - php

Can somebody tell me what am I missing here for the code to display data from my database? Much appreciated!
HTML
<!DOCTYPE html>
<html lang="en" ng-app="VinylApp">
<head>
<meta charset="utf-8">
<title>Vinyl Record Store</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="script.js"></script><script src="app.js"></script>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div ng-app="VinyApp" ng-controller="VinylListController">
<table>
<tr ng-repeat="vinyl in vinyls">
<td>{{vinyl.Vinyl_ID}}</td>
<td>{{vinyl.VinylName}}</td>
<td>{{vinyl.Artist}}</td>
<td>{{vinyl.Price}}</td>
</tr>
</table>
</div>
</body>
</html>
JS
var app= angular.module('VinylApp', []);
app.controller('VinylListController', function($scope, $http){
$http.get("db_con.php")
.then(function(response){
$scope.vinyls = response.data.records;
});
});
PHP
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type:application/json; charset=UTF-8");
$conn = new mysqli("myServer","myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT * FROM vinyl");
$outp= "";
while($rs=$result->fetch_array(MYSQLI_ASSOC)){
if ($outp != "") {$outp .= ",";}
$outp .= '{"VinylID":"' . $rs["VinylID"] . '",';
$outp .= '"VinylName":"' . $rs["VinylName"] . '",';
$outp .= '"Artist":"'. $rs["Artist"] . '",';
$outp .= '"Price":"'. $rs["Price"] . '"}'; } $outp ='{"records":['.$outp.']}'; $conn->close();
echo($outp);
}
?>

i have solve issue. Please try this code is working g fine for me. here add new angular.min.js and some changes added
var app= angular.module('VinylApp', []);
app.controller('VinylListController', function($scope, $http){
$http.get("db_con.php")
.then(function(response){
$scope.vinyls = response.data;
});
});
<!DOCTYPE html>
<html lang="en" ng-app="VinylApp">
<head>
<meta charset="utf-8">
<title>Vinyl Record Store</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular.min.js"></script>
<script src="app.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="VinyApp">
<div ng-controller="VinylListController">
<table>
<tr ng-repeat="vinyl in vinyls">
<td>{{vinyl.Vinyl_ID}}</td>
<td>{{vinyl.VinylName}}</td>
<td>{{vinyl.Artist}}</td>
<td>{{vinyl.Price}}</td>
</tr>
</table>
</div>
</body>
</html>
<?php
$conn = new mysqli("localhost","root", "", "pinakin_northwind");
$result = $conn->query("SELECT * FROM vinyl");
$outp = array();
while( $rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = $rs;
}
echo json_encode($outp);
?>

Related

find records in sql with same id as html button's id and generate a modal

The problem is that I have an html table with short info about employees that is taken from MySQL database. I'm trying to make a button with some ID that will open a modal window with full info about employee with the same value in it's field called 'ButtonID'. I tried to make desired query and set it to some variable in php and then access it in javascript but it didn't end well.
<!--
in <input id = "1" type="button" value="Full Info" input id equals to sql
'ButtonID' fields value
-->
Edit:
<form action="">
<input id = "1" type="button" value="Full Info"
onclick="fullInfo()">
</form>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Список сотрудников</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class = "header">
<img src = "img/header.png"></img>
</div>
<div class = "container">
<?php
echo "<table id='table_id' class = 'table table-striped'>";
echo "<thead>
<tr>
<th>№</th>
<th>ФИО</th>
<th>Имя транслитом</th>
<th>Дата рождения</th>
<th>Должность</th>
<th>Дата приёма</th>
<th>№ удостоверения</th>
<th>Полная информация</th>
</tr>
</thead>
";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT number, fullname, engname,birthdaydate, position, recruitmentDate,id,buttonid FROM employees");
$ids = $conn->prepare("SELECT * FROM employees");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
</div>
<div class = "footer">
<img src = "img/footer.jpg"></img>
</div>
<!--<link rel="stylesheet" type="text/css" href="css/styles.css">-->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$('#table_id').DataTable( {
"language": {
"url": "//cdn.datatables.net/plug-ins/1.10.13/i18n/Russian.json"
}
} );
} );
</script>
<!--
<script>
function fullInfo(){
var ids = <?php echo json_encode($ids); ?>;
for (int i = 0;i<ids.length;i++){
if (ids['buttonID'] == this.id){
alert ("good");
}
}
};
</script>
-->
</body>
</html>
You create a function that will process a call to your site like this:
http://my-site.com/employee.php?id=12
employee.php (idea)
$stmt = $conn->prepare("SELECT * FROM employees WHERE id=:id");
$stmt->execute(array(':id' => $_GET['id']));
$employee = $stmt->fetch(PDO::FETCH_ASSOC);
print "<ul>";
//list the employee data
foreach($employee as $key => $value)
{
$key = htmlspecialchars($key, ENT_QUOTES, 'UTF-8');
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8')
print "<li>". $key .': ' . $value . '</li>';
}
print "</ul>";
I suggest you to use an <a> tag instead of <button> as you have a link here, not a form. Just stylize it with CSS. In the column "Полная информация" of your table create a link:
<a target="_blank" href=\"/employee.php?id=$row['id']\">Полная информация</a>
This will open a new page. Process the request with PHP, I gave you the sample code.
Then add the ornaments like making the window modal, changing it's size etc.
For each row echo a button with its id as the employees id.
Add a letter before the id on the button to make sure it doesn't get repeated.
echo "<button id='emp*$employeeid*'>view</button>

JSON data with AngularJS from PHP connecting to SQL

connect.php
<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=Northwind";
$credentials = "user=postgres password=qwer1234";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from customers;
EOF;
$ret = pg_query($db, $sql);
if(!$ret){
echo pg_last_error($db);
exit;
}
$rows = array();
while($r = pg_fetch_assoc($ret)){
$rows[] = $r;
echo json_encode($rows);
}
?>
JSON
[{"CustomerID":"ALFKI","CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative","Address":"Obere Str. 57","City":"Berlin","Region":null,"PostalCode":"12209","Country":"Germany","Phone":"030-0074321","Fax":"030-0076545"}][{"CustomerID":"ALFKI","CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative","Address":"Obere Str. 57","City":"Berlin","Region":null,"PostalCode":"12209"...........
AngularJs.html
<html ng-app="myApp">
<head>
<title></title>
<meta charset="utf-8" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-controller="customersCtrl">
<div>
<table class="table table-striped">
<thead>
<tr>
<th>CustomerID</th>
<th>CompanyName</th>
<th>ContactName</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in customers">
<td>{{item.CustomerID}}</td>
<td>{{item.CompanyName}}</td>
<td>{{item.ContactName}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</html>
<script>
var app = angular.module("myApp", []);
app.controller('customersCtrl', ['$scope', '$http', function($scope,$http) {
console.log("Initiating the controller");
$http.get('http://localhost:8080/connect.php').success(function(data) {
$scope.customers = data;
});
}]);
</script>
The result of this is that nothing shows up on angularjs.html Help Me! Thanx.
Initiating the controller
XMLHttpRequest cannot load http://localhost:8080/connect.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

How to display data using AngularJS with php

I want to connect my index.php page with ngconnect.php and want to display my table record.
This is my index.php page below.................
<html>
<head>
<title>first ng app recieve data from database</title>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body ng-app="myapp" ng-controller="myctrl">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
<script>
$(function(){
var app = angular.module('myapp',[]);
app.controller('myctrl',function($scope,$http){
$http({method:'GET', url:'ngconnect.php'}).success(function(response){
$scope.names = response;
});
});
});
</script>
</body>
</html>
This is my ngconnect.php page below.............
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = mysql_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
} else {
$db_selected = mysql_select_db('dsc');
if (!$db_selected) {
die ('Can\'t use dsc : ' . mysql_error());
} else {
$result = mysql_query('SELECT * from user');
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
echo json_encode($data);
}
}
}
mysql_close($conn);
?>
Why my data is not being display?
ngconnect.php does display the following.....
[{"0":"1","user_id":"1","1":"Amit","first_name":"Amit","2":"","middle_name":"","3":"Kushwaha","last_name":"Kushwaha","4":"akushwaha.softvisionindia#gmail.com","email":"akushwaha.softvisionindia#gmail.com","5":"2","rate_dsc_2":"2","6":"3","rate_dsc_3":"3","7":"4","rate_token":"4","8":"e10adc3949ba59abbe56e057f20f883e","password":"e10adc3949ba59abbe56e057f20f883e","9":"Enabled","status":"Enabled","10":"8858234949","phone":"8858234949","11":"NULL","forget_link":"NULL","12":"00:00:00","forget_time":"00:00:00"},{"0":"2","user_id":"2","1":"Sandeep","first_name":"Sandeep","2":"","middle_name":"","3":"Tripathi","last_name":"Tripathi","4":"sandeep.softvisionindia#gmail.com","email":"sandeep.softvisionindia#gmail.com","5":"10","rate_dsc_2":"10","6":"20","rate_dsc_3":"20","7":"30","rate_token":"30","8":"e10adc3949ba59abbe56e057f20f883e","password":"e10adc3949ba59abbe56e057f20f883e","9":"Enabled","status":"Enabled","10":"9936882864","phone":"9936882864","11":"","forget_link":"","12":"00:00:00","forget_time":"00:00:00"}]
Try these codes..Hope it will help You..
I assume that your responce is in json format (array of object) as you posted your responce of php file..
<html>
<head>
<title>first ng app recieve data from database</title>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body ng-app="myapp" ng-controller="myctrl">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
<script>
var myapp = angular.module('myapp', []);
myapp.controller('myctrl', function ($scope, $http) {
$http.get('ngconnect.php').success(function(data) {
$scope.names = data;
});
});
</script>
</body>
</html>

flot ,and mysql jquery

I have a problem using flot to plot data from a database.
using json_encode in php I have tried to get the plot data but I have been unsuccessful.
Below is my code, kindly assist
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>`enter code here`
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="./flot/layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="./flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="./flot/jquery.flot.js"></script>
</head>
<body>
<h1>Database Plotting</h1>
<div id="placeholder" style="width:600px;height:300px;"></div>
<?php
$server = "localhost";
$user="user";
$password="password";
$database = "database";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
$query = "SELECT x_value, y_value FROM table";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($row['x_value'],$row['y_value']);
}
?>
<script type="text/javascript">
$(function () {
var dataset1 = <?php echo json_encode($dataset1,); ?>;
$.plot($("#placeholder"),[dataset1] );
});
</script>
</body>
</html>
The ouput from the json-encode dataset1 is thus the following [["1380111342","0"],["1380111679","0"],["1380112099","20"],["1380112109","300"],["1380112114","40"],["1380112120","56"],["1380112127","36"],["1380112132","40"],["1380112138","78"]]
Try change this line:
$.plot($("#placeholder"), [dataset1] );
To that:
$.plot($("#placeholder"), [JSON.parse(dataset1)]);
var dataset1 = <?php echo json_encode($dataset1,); ?>;
Lose the comma after "$dataset1" and the semi-colon at the end.
This should work just fine:
var dataset1 = <?php echo json_encode($dataset1); ?>

jquery simple pager with first , last

<code>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery.pager.js Test</title>
<link href="Pager.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery.pager.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#pager").pager({ pagenumber: 1, pagecount: 15, buttonClickCallback: PageClick });
});
PageClick = function(pageclickednumber) {
$("#pager").pager({ pagenumber: pageclickednumber, pagecount: 15, buttonClickCallback: PageClick });
$("#result").html("Clicked Page " + pageclickednumber);
}
</script>
</head>
<body>
$query = "select name from student";
$result = mysql_query(Query);
while($row=mysql_fetch_array($result)){
$student_name = $row['name'];
?>
<h1 id="result"><?php echo $student_name; ?></h1>
<? }
?>
<div id="pager" />
</body>
</html>
</code>
For my above code am not geting the student name , if i remove the pager script , the student name will appear, may i know , why, where i made mistake..
i thing i have to pass somthing to html() , but i am not sure..
while($row=mysql_fetch_array($result)){ $student_name = $row['name']; }
should be
$student_name = NULL;
while($row=mysql_fetch_array($result)){ $student_name .= $row['name']; }

Categories