I am trying to connect my angularjs application to a simple php script which is simply returning a sql query from sqlite3 database.
Here is my PHP script:
<?php
date_default_timezone_set('UTC');
try {
$objDb = new PDO('sqlite:../dbase/shopper');
$objDb -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT item.* ,
t.name AS type_name
FROM items item
INNER JOIN types t
ON t.id = item.type
ORDER BY item.date ASC";
$result = $objDb->query($sql);
if(!$result) {
throw new PDOException("The result returned no object");
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$items = $result->fetchAll();
$sql = "SELECT *
FROM types
ORDER BY id";
$result = $objDb->query($sql);
echo var_dump($result);
if(!$result) {
throw new PDOException("The result returned no object");
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$types = $result->fetchAll();
echo json_encode(array(
'error' => false,
'items' => $items,
'types' => $types
), JSON_HEX_TAG | JSON_HEX_APOS |JSON_HEX_QUOT |JSON_HEX_AMP );
} catch (PDOException $e) {
echo json_encode(array(
'error' => true,
'message' => $e->getMessage()
),JSON_HEX_TAG | JSON_HEX_APOS |JSON_HEX_QUOT |JSON_HEX_AMP );
}
When I check the php file address I can get the result :
object(PDOStatement)#3 (1) { ["queryString"]=> string(41) " SELECT * FROM types ORDER BY id " }
{"error":false,"items":[{"id":"1","item":"Butter","qty":"1","type":"1","done":"0","date":"2014-10-06 02:45:51","type_name":"Qty"}],"types":[{"id":"1","name":"Qty"},{"id":"2","name":"Kg"}]}
If I use angularjs I get undefined results.
.controller('ShoppingListController', function($scope, $http, $log ){
$scope.types = [];
$scope.items = [];
$scope.item = '';
$scope.qty = '';
$scope.types = '';
$scope.select = function( ) {
$http({method: 'GET',url: 'mod/select.php'})
.success(function(data){
console.log(data)
$scope.items = data.items;
if(data.types) {
$scope.types = data.types;
$scope.type = $scope.types[0].id;
}
})
.error(function(data,status,header){
throw new Error('Something went wrong with selecting record');
});
};
$scope.select();
});
console.log(data) shows :
object(PDOStatement)#3 (1) {
["queryString"]=>
string(41) " SELECT *
FROM types
ORDER BY id "
}
{"error":false,"items":[{"id":"1","item":"Butter","qty":"1","type":"1","done":"0","date":"2014-10-06 02:45:51","type_name":"Qty"}],"types":[{"id":"1","name":"Qty"},{"id":"2","name":"Kg"}]}
How can I fix this ?
You must return a JSON response. Fetch an associative array from your database and return this:
echo json_encode($db_query);
In Angular, you can then set the scope equal to the response ex:
$scope.items = data.items;
You can then access this in your view (be sure to have ng-controller="ShoppingListController").
To iterate over the data:
ng-repeat="item in items"
You can then access each piece via item.id or whatever your key in the array may be.
Also, no need to set $scope.items at the top.
Edit:
.controller('ShoppingListController', function($scope, $http, $log) {
function select() {
$http.get('mod/select.php')
.success(function(data) {
$scope.items = data.items;
if(data.types) {
$scope.types = data.types;
$scope.type = $scope.types[0].id;
}
});
}
select();
});
Remove the var_dump(); And BTW you don't need to echo with var_dump(), it already appends to the output buffer. The var_dump() makes your response invalid JSON.
Related
I have passed values using post from Angular component to PHP and able to view the passed input values but when using inputs in select query unable to fetch any records
PHP Code:
$json = file_get_contents('php://input');
$obj = json_decode($json);
$selectedDept = filter_var($obj->selectyear, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$selectedYear = filter_var($obj->selectDepart, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$searchdata = array();
try {
$stmt = $pdo->prepare('SELECT * FROM circular_data WHERE YEAR(Circular_date)=:selectyear AND Circular_department=:selectDepart');
$stmt->bindParam(':selectyear', $selectedYear);
$stmt->bindParam(':selectDepart', $selectedDept);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
// Assign each row of data to associative array
$searchdata[] = $row;
}
echo json_encode($searchdata);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Component Class code where inputs passed using POST request:
this.selectedData = {
selectyear: this.selectedYear,
selectDepart: this.selectedDepartment
}
let selectData = this.selectedData;
this.http.post('http://localhost:8080/dbcon/retrieve-searchdata.php', selectData, httpOptions)
.subscribe((searchdata : any) =>
{
console.log(searchdata);
},
err => {
console.log("Error occured", err);
}
);
i am trying to create a service that will return a json data from php api, but instead of return pure json data, the angular seem to return JSON together with its config.
services.js
.service('DistinctAPIService', function($http){
var base = 'http://localhost/onseral/api/';
this.listDistinct = function(table, field){
return $http({
method: 'POST',
url: base + '/listDistinct.php',
params: {
table: table,
field: field
}
});
}
})
.controller('DistinctMatcode', function($scope, DistinctAPIService){
DistinctAPIService.listDistinct('material', 'matcode').then(function(data){
$scope.data = data;
console.log(JSON.stringify(data));
})
})
listdistinct.php
<?php
require_once '/config/dbconfig.php';
$table = $_GET['table'];
$field = $_GET['field'];
GetData($table,$field);
function GetData($tablename,$fieldname) {
$sql = "SELECT DISTINCT $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>
instead of returning the correct JSON data, it returned
{"data":{"data":[{"expr1":"CFFBPS16"}]},"status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://localhost/onseral/api//listDistinct.php","params":{"table":"material_copy","field":"matcode"},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
any idea?
try this
controller('DistinctMatcode', function($scope, DistinctAPIService){
DistinctAPIService.listDistinct('material', 'matcode').then(function(response){
$scope.data = response.data.data;
console.log(JSON.stringify(data));
})
Use header function before sending data to the client side.
i modified your listdistinct.php file. try it , let me know if issue persist.
<?php $sql = "SELECT DISTINCT $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
header('Content-Type: application/json');
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>
I'm trying to read some information from a MySQL database using php and then pass the results to jquery and log them in the console.
To read from the database I use:
public function getQuestions(){
$query = 'SELECT * FROM Question';
$statement = $this->db->prepare($query);
$statement->execute();
$questions = [];
while($row = $statement->fetch()){
$questions[] = array(
'QuestionID' => $row['QuestionID'],
'Content' => $row['QuestionContent']
);
}
return $questions;
}
where $this->db is a PDO object.
Then this method is called from
<?php
include_once 'classes/DatabaseAdapter.php';
$dba = new DatabaseAdapter();
echo $dba->getQuestions(); // Array to String conversion error.
And that is then called from jQuery with:
$.ajax({
url: 'questions.php',
method: 'post'
}).done(function(data){
console.log('done');
console.log(data);
});
The problem I'm having is when I encode the output as json in PHP with json_encode() I get an empty string in the console and decode it in jQuery with JSON.parse(). Then I try passing it without encoding and get a notice saying Array to String conversion in PHP line with echo.
Try this way. You can adapt the code to your getQuestions() function
Php code
//PDO connection
$host = "";
$user = "";
$dbname = "";
$pass = "";
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
//PDO Database query and Json encode
$STH = $DBH->prepare("SELECT * FROM Question");
$STH->execute();
$result = $STH->fetchAll();
$data = array();
$data['items'] = $result;
echo json_encode($data);
Jquery
//$.getJSON is a shorthand Ajax function
$.getJSON("questions.php", function(data) {
console.log(data);
$.each(data.items, function(i, value){
console.log(value.thecolumnnameinmysqltable);
})
})
In the Php im creating an array for the purpose that you can add extra data and retrieve it .eg
$data = array();
$data['data'] = array("one", "two", "three", "four");
$data['items'] = $result;
echo json_encode($data);
and to retrieve the $data['data'] array in Jquery you do
var one = data.data[0];
var two = data.data[1];
var three = data.data[2];
var four = data.data[3];
Getjson info -- http://api.jquery.com/jquery.getjson/
Try this.
echo json_encode($dba->getQuestions());
exit;
I have another problem with my code.
<script type="text/javascript">
$("#wojewodz").change(function(){
var id_wojewodztwa = $("#wojewodz").children(":selected").attr("id");
$.post("miasta.php", { id_wojewodztwa: id_wojewodztwa } );
$('#powiat_miasto_auto_complete').autocomplete({source:'miasta.php', minLength:2});
});
</script>
this is functions which get ID of selected select and transfering it to miasta.php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass, $options);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if (($conn) and (isset($_GET['id_wojewodztwa'])))
{
$id_wojewodztwa = $_GET['id_wojewodztwa'];
$ac_term = "%".$_GET['term']."%";
$query = "SELECT DISTINCT nazwa FROM podzial_tm where woj='$id_wojewodztwa' and nazdod!='województwo' and nazwa like :term LIMIT 10";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['value'] = $row['nazwa'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
somebody can tell me where is some mistake?
when i change " where woj='$id_wojewodztwa'" to for example " where woj='26'" and delete " and (isset($_GET['id_wojewodztwa']))" everything is ok, so i think i have problem with POST
happy Easter! :)))
You are POSTing the data. You need to look in $_POST['id_wojewodztwa'] for the value you are looking for, not in $_GET.
$.post("miasta.php", { id_wojewodztwa: id_wojewodztwa } );
to
$.get("miasta.php", { id_wojewodztwa: id_wojewodztwa } );
or if you have to catch up the result, use:
$.get("miasta.php", { id_wojewodztwa: id_wojewodztwa },function(result){
/** some code here */
},'json');
UPDATE:
if you use $.post, edit the following lines:
if (($conn) and (isset($_POST['id_wojewodztwa'])))
{
$id_wojewodztwa = $_POST['id_wojewodztwa'];
Remove isset($_GET['id_wojewodztwa']) and also modify $id_wojewodztwa = intval($_GET['id_wojewodztwa']);
I am constructing an API with Javascript and for security reasons I switched my PHP database calls over to PDO.
Since doing so, I have had troubles with queries returning empty arrays (NOTE: not MySQL syntax errors). The latest example is this:
/*JAVASCRIPT*/
var getSampleEntity = function(params) {
//Returns Object
return $.ajax({
url: URL + 'downloadQuadrat_Organism.php',
type: 'POST',
data: { 'organismID': params.oid, 'quadratID': params.qid },
dataType: dataType
});
}
Header data sent from browser:
/*PACKAGE HEADER INFO*/
Request URL:http://..../downloadQuadrat_Organism.php
Request Method:POST
Status Code:200 OK
...
Form Data:
organismID:3
Which is sent to server...
/*PHP*/
//Init
$resultset = array();
$quadratID = $_POST['quadratID'];
$organismID = $_POST['organismID'];
$sql = 'SELECT * FROM Quadrat_Organism WHERE organismID = :organismID OR WHERE quadratID = :quadratID';
//Main
try{
$db = connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':quadratID', $quadratID);
$stmt->bindParam(':organismID', $organismID);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$resultset[] = $row;
//Return result in JSON
$resultset = json_encode($resultset);
print_r($resultset);
} catch(PDOException $e){
print 'Error!: '.$e->getMessage().'<br/>';
}//End try catch
$db = null;
I expect an array of results in JSON (dummy-data in database should return 5 results), instead I receive [] (empty JSON array).
I believe the issue is at the PHP level, but I cannot identify the issue.
you have an error in your where Condition MySQL query:
Try this out, use this
$sql = 'SELECT * FROM Quadrat_Organism
WHERE organismID = :organismID OR quadratID = :quadratID';
instead of:
$sql = 'SELECT * FROM Quadrat_Organism
WHERE organismID = :organismID OR WHERE quadratID = :quadratID';
use only one where in your queries.