How do I display the MySQL data in Angular - php

I've been trying to learn some SQL for my covid-19 timepass and I managed to make data and all but I'm now stuck with this, I'm lost on how to repeat with angular the table that I got from my SQL DB in the TABLE BELOW!, I looked at W3School and couple other websites but I didn't get it.
PHP
if($connectServer->connect_error){
die("Connection failed :".$connectServer->connection_error);
}
$result = $connectServer->query("SELECT * FROM Users");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"ID":"' . $rs["userID"] . '",';
$outp .= '"First Name":"' . $rs["FName"] . '",';
$outp .= '"Last Name":"' . $rs["FName"] . '",';
$outp .= '"City":"' . $rs["City"] . '",';
$outp .= '"Email":"'. $rs["Email"] . '"}';
}
$outp ='{"names":['.$outp.']}';
echo($outp);?>
HTML
<table ng-controller="customersCtrl" ng-app="myApp">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>City</th>
<th>Email</th>
</tr>
<tr ng-repeat="a in names">
<td>{{a.ID}}</td>
<td>{{a.First Name}}</td>
<td>{{a.LName}}</td>
<td>{{a.City}}</td>
<td>{{a.Email}}</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("php/fetchDATA.php")
.then(function (response) {$scope.names = response.data.records;});
});
</script>
fetchDATA.PHP
{"names":[{"ID":"32","First Name":"ValueFName","Last Name":"ValueFName","City":"ValueCity","Email":"ValueEmail"},{"ID":"33","First Name":"ValueFName","Last Name":"ValueFName","City":"ValueCity","Email":"ValueEmail"},{"ID":"34","First Name":"ValueFName","Last Name":"ValueFName","City":"ValueCity","Email":"ValueEmail"}]}

There are some mistakes in each of your code like variable {{a.First Name}} having space and {{a.LName}} is not defined anywhere.
So you must change the variable declaration in php for the code to work.
Further the response you are expecting must have the variable records but the php you have defined does not have any such variable. Thus I will suggest you to read PHP and Angular tutorial again before asking the question.

Related

Search bar not functioning properly

My problem is when I enter a specific country name, for example: France, it'll output every data from my database instead of just France. I don't know where I've gone wrong and its probably something very simple but I don't even know how to attempt to fix it so I've come here to get some help
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$country = $_POST['country'];
$_SESSION['country'] = $country;
$sqlQuery = "SELECT * FROM campsites WHERE country LIKE '%$country%'";
$result = $campDataSet->fetchAllCamps($sqlQuery);
//var_dump($result);
if (count($result) > 0) {
echo'<div class="table-responsive">
<table class="table">
<thead id="table1Head">
<tr><td>Name</td>
<td>Address</td>
<td>Postcode</td>
<td>Country</td>
<td>Latitude</td>
<td>Longitude</td>
<td>email</td>
<td>Phone<td>
</thead>
<tbody>
</div>';
foreach ($result as $row) {
echo '<tr><td>' . $row->campsite_name . '</td> <td>' . $row->address . '</td> <td>' . $row->postcode . '</td> <td>' . $row->country. '</td> <td>' . $row->lattitude . '</td> <td>' . $row->longitude . '</td> <td>' . $row->email . '</td> <td>' . $row->phone_number . '</td></td></tr>';
}
echo "</tbody></table>";
} else {
print " 0 results";
}
}
my Database class
class campDataSet
{
public $dbHandle, $dbInstance;
public function __construct()
{
$this->db = new campData();
$this->conn = $this->db->getCampData();
}
public function fetchAllCamps()
{
//$sqlQuery = "SELECT campsites.id_campsite, campsites.campsite_name, campsites.address, campsites.postcode, campsites.country, campsites.lattitude, campsites.longitude, campsites.email, campsites.phone_number
// FROM sgb220_clientserver.campsites";
$sqlQuery = "SELECT * FROM sgb220_clientserver.campsites";
if ($data = $this->conn->prepare($sqlQuery)) {
$data->execute();
$dataSet = [];
while ($row = $data->fetch()) {
$dataSet[] = new DBdata($row);
}
} else {
echo "<script> alert(\"Could not prepare SQL statement\") </script>";
}
return $dataSet;
}
Your fetchAllCamps() method doesn't accept any arguments.
Instead of defining the $sqlQuery inside fetchAllCamps, use a parameter:
public function fetchAllCamps($sqlQuery) // <- This
{
if ($data = $this->conn->prepare($sqlQuery)) {
$data->execute();
$dataSet = [];
...
A warning about SQL Injection
Because you are inserting $_POST data directly into your query, the user is able to manipulate the sql and thus can extract/manipulate data however he wants to. Read up in SQL Injection and how to prevent it to keep your database safe from attackers.
This might be a good starting point: https://stackoverflow.com/a/601524/2232127
Your issue is that you are running a query that just gets all of the camps instead of only the ones in a certain country. Your fetchAllCamps() function does not accept any parameters.
It would probably be best to move your query into the fetchAllCamps() function, or make another function entirely if you need a function to give you all the camps instead o just ones in a certain country. Instead of passing in the query, just pass the $country variable. Build your query inside the function and run it.
This way you are separating all of your SQL from where you are building your HTML. This is more in line with modern programming standards.

JSONP in Angularjs [duplicate]

This question already has answers here:
Unexpected token colon JSON after jQuery.ajax#get
(2 answers)
Closed 4 years ago.
I want to get data from my Database into my Angluar.js.
So i created a php file, which selects my data.
I read that i have to use jsonp, elsewhise i will not get the data.
data.php
<?php
$db = mysqli_connect("xxx", "xxx", "xxx", "xxx");
$select = "select * from product;";
$result = mysqli_query($db,$select);
if ($result) {
$i=0;
$outp = "";
while ($row = mysqli_fetch_assoc($result))
{
if ($outp != "") {$outp .= ",";}
$outp .= '"preis":"' . $row["preis"] . '",';
$outp .= '"name":"'. $row["name"] . '"}';
}
$outp ='{"records":['.$outp.']}';
echo($outp);
}
?>
App.js
var url = "http://server/data/data.php?callback=JSON_CALLBACK"
$http.jsonp(url)
.success(function(data){
console.log(data.found);
});
Now i get a syntax error:
"SyntaxError: unexpected token: ':'"
Thanks for your help
Don't build JSON by yourself. Try this instead. Main thing is, just create an array the way you'd like it, then use json_encode()
$result = [];
while ($row = mysqli_fetch_assoc($result))
{
$result[] = $row;
}
echo json_encode($result);

How to get postal code by address

I would like to get the postal code by enter address, I have tried google auto complete place search, But it gives wrong postal code for some places.
Give any idea to get the correct postal code by the given address?
Thank you,
Try below code this may be helps to you:
// Decode json
$decoded_json = json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false'));
foreach($decoded_json->results as $results)
{
foreach($results->address_components as $address_components)
{
// Check types is set then get first element (may want to loop through this to be safe,
// rather than getting the first element all the time)
print_r($address_components);
if(isset($address_components->types) && $address_components->types[0] == 'postal_code')
{
// Do what you want with data here
echo $address_components->long_name;
}
}
}
Use below code it will help you.
<?php
$db = mysqli_connect("localhost","root","") or die("Could not connect");
mysqli_select_db($db, "search_db") or die("No database");
$textbox = "";
$out = "";
$title = "";
if (isset($_GET['search'])) {
$searchq = $_GET['search'];
$query = mysqli_query($db, "SELECT * FROM `pincodes_db` WHERE `pincode` LIKE '%$searchq%' OR `divisionname` LIKE '%$searchq%' OR `statename` LIKE '%$searchq%' OR `regionname` LIKE '%$searchq%' OR `officename` LIKE '%$searchq%' OR `circlename` LIKE '%$searchq%'" ) or die("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = 'There was no records found';
}else{
while($row = mysqli_fetch_array($query)){
$pincode = $row['pincode'];
$officename = $row['officename'];
$Deliverystatus = $row['Deliverystatus'];
$divisionname = $row['divisionname'];
$Taluk = $row['Taluk'];
$RelatedHeadoffice = $row['RelatedHeadoffice'];
$RelatedSuboffice = $row['RelatedSuboffice'];
$circlename = $row['circlename'];
$regionname = $row['regionname'];
$contactno = $row['Telephone'];
$out .= '<div style="border-bottom:1px dotted green;">
<h2 style="font-size:18px;"><a href="search-indian-postal-code-in-map.php?postalcodeof='.$pincode.'"/><b><font color="green">Postal code of :</font></b><b><font color="green">'.$pincode.'</font></b> <b><font color="green">'.$officename.'</font></b> <b><font
color="green">'.$regionname.'</font>,</b> <b><font color="green">'.$circlename.'</font>,</b> <b><font color="green">'.$contactno.'</font></b></a></h2>
<table><tr><th>Description</th><th>Result</th></tr><tr>
<td>Pincode</td>
<td>' .$pincode.'</td></tr>
<td>Office Name</td>
<td>' .$officename. '</td></tr>
<td>Delivery system</td>
<td>' . $Deliverystatus. '</td></tr>
<td>Division Name</td>
<td>' . $divisionname. '</td></tr>
<td>Taluk</td>
<td>' . $Taluk. '</td></tr>
<td>Related Head Office</td>
<td>' . $RelatedHeadoffice. '</td></tr>
<td>Related Sub Office</td>
<td>' . $RelatedSuboffice. '</td></tr>
<td>Circle Name</td>
<td>' . $circlename. '</td></tr>
<td>Region</td>
<td>' . $regionname. '</td></tr>
<table/></div>';
}
}
}
?>
i have used same code for my website Please refer
http://www.myworkbook.in/indian-postal-code-search/indian-states.php

Get Data from PHP in angular unhandled error

I get an error which doesn't say anything to me. I'm kinda new to Angular so it might be a really stupid error but I can't figure out.
It says there's a Syntax Error:
SyntaxError: Unexpected token /
at Object.parse (native)
at fromJson (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:1252:14)
at defaultHttpResponseTransform (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:9414:16)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:9505:12
at forEach (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:336:20)
at transformData (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:9504:3)
at transformResponse (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:10276:23)
at processQueue (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:14745:28)
at https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:14761:27
at Scope.$eval (https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js:15989:28)
My html Code where I'm calling the controller:
<div ng-controller="dbTestCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
My Angular controller:
module.controller('dbTestCtrl', function($scope, $http) {
$http.get(PHP_API + "datahandler/dbTest.php")
.then(function (response){
$scope.names = response.data.records;});
});
And my php file which is working as far as i can see:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "", "cmweb");
$result = $conn->query("SELECT loginName, userID, createDate FROM users");
$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {
$outp .= ",";
}
$outp .= '{"Name":"' . $rs["loginName"] . '",';
$outp .= '"ID":"' . $rs["userID"] . '",';
$outp .= '"Created":"'. $rs["createDate"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
As I said I'm really new to angular and I just couldn't figure out by myself so it would be great if someone could help me out :)
Thx
May be your json format is wrong. Try using json_encode to avoid writing all those quotes and brackets by yourself.
$outp = array();
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = array('Name' => $rs["loginName"],
'ID' => $rs["userID"],
'Created' => $rs["createDate"]);
}
echo json_encode(array('records' => $outp));

Angular crashing while there is a "Enter" in json file

So basically i have json file made from SLQ database by PHP script
Geting angular to read json and binds to scope
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://kserwach.nazwa.pl/extremerun/data.php")
.success(function (response) {$scope.names = response.records;});
});
You can look at json file by simply enterning this link
[http://kserwach.nazwa.pl/extremerun/data.php][1]
My problem is that, while i put any "new line" in SQL angular crashes. How can i make angular to not crash while someone press "enter button" while writing new desc? Or else how to make json file to replace this "enter" with some html tag, and then how to make angular to read this html tag?
This is how i read mySQL data
<?php
$user='user_name';
$password='password';
$dbname='db_name';
$host='host';
try
{
$db = new PDO('mysql:host='.$host.';dbname='.$dbname.';',$user,$password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>"; die();
}
$stmt = $db-> query('SELECT name,description,surname,photo FROM mates');
$temp = 0;
$outp = "";
foreach($stmt as $row)
{
if($temp == 0) {
$outp .= '{"Name":"'.$row['name'].'",';
$outp .= '"Photo":"'.$row['photo'].'",';
$outp .= '"Surname":"'.$row['surname'].'",';
$outp .= '"Desc":"'.$row['description'].'"}';
$temp = 1;
} else {
$outp .= ',{"Name":"'.$row['name'].'",';
$outp .= '"Photo":"'.$row['photo'].'",';
$outp .= '"Surname":"'.$row['surname'].'",';
$outp .= '"Desc":"'.$row['description'].'"}';
}
}
$outp ='{"records":['.$outp.']}';
echo($outp);
?>
And then, sorry for my bad english. Just not primary, or even secondary language.

Categories