how to receive data from a php file into angularjs code - php

I am calling the php file from js code from http.get in angularjs. On Success function the result should be received in parameter. But it is showing that null is received.If I use simple echo with a string param that is received but the sql result is not received in function. The query and connection is correct. I am unable to find the error.
js file
app.controller('HomeController',function($scope,$http){
$scope.message="Home";
$http.get('get.php').
success(function(data) {
debugger;
$scope.users = data;
});
});
php file
<?php
$database = "firstdatabase"; //database name
$con = mysqli_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$state = "SELECT rollno ,name, dept FROM student";
$result = mysqli_query($con, $state);
if ($result) {
$arr = array();
while ($row = mysqli_fetch_array($result)) {
//$r[] = $row['rollno'];
//$n[]= $row['name'];
//$d[] = $row['dept'];
$arr[] = $row;
}
//$rows = array();
// while($row = $result->fetch_row()) {
// $rows[]=$row['name'];
// }
}
echo htmlspecialchars(json_encode($arr));
?>

Your echo statement is in the last line, However in the middle of your php code, you've placed an unconditional exit(); statement that's preventing this script to execute completely and thus is preventing it to echo the response.

Related

Output a JSON in PHP generated on SQL SERVER with JSON AUTO

I am trying to get the output of a JSON formatted on SQL SERVER through command FOR JSON AUTO
I need to execute the query in PHP on SQL SERVER and then output it as a legit JSON.
How should I proceed?
I normally use the code below to generate the JSON, but what if I need to get a JSON ?
$key= $_GET['key'];
$date=$_GET['date'];
$brand=$_GET['brand'];
if ($key=="...")
{
$serverName = "XXX,YYYY"; // \\MSSQLSERVER";
$connectionOptions = [
"Database" => "db",
"UID" => "user",
"PWD" => 'xxxx'
];
$conn = sqlsrv_connect($serverName, $connectionOptions);
if ($conn === false) {
die(formatErrors(sqlsrv_errors()));
}
$tsql = "select * from admin_all.Datafeed FOR JSON AUTO;";
// Executes the query
$stmt = sqlsrv_query($conn, $tsql);
// Error handling
if ($stmt === false) {
die(formatErrors(sqlsrv_errors()));
}
$array = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$array[]=$row;
}
echo json_encode(array("data"=>array_values($array)));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}
The reason for the unexpected result is that json_encode() call is not needed (but it's always an option). FOR JSON AUTO returns a valid JSON, so you only need to echo the generated JSON. Note, that if you want to add a single, top-level element to the JSON output of the FOR JSON clause, you need to use the ROOT option.
Example, based on your attempt:
<?php
...
$json = '';
if ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_BOTH)) {
$json = $row[0];
}
echo '{"data":'.$json.'}';
...
?>
Example with json_encode():
<?php
...
$sql = "SELECT id FROM (VALUES (1), (2)) v(id)";
$stmt = sqlsrv_query($conn, $sql);
if($stmt == false){
die( print_r( sqlsrv_errors(), true) );
}
$json = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$json[] = $row;
}
echo json_encode(array("data" => array_values($json)));
...
?>
Example with FOR JSON AUTO and the ROOT option:
<?php
...
$sql = "SELECT id FROM (VALUES (1), (2)) v(id) FOR JSON AUTO, ROOT('data')";
$stmt = sqlsrv_query($conn, $sql);
if($stmt == false){
die( print_r( sqlsrv_errors(), true) );
}
$json = '';
if ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
$json = $row[0];
}
echo $json;
...
?>
Generated JSON:
{"data":[{"id":1},{"id":2}]}
PHP example;
// This file is to be called by AJAX
<?php
require_once('db.php');
$select = mysqli_query($con, "select * from table where index='something'");
$row[]=mysqli_fetch_array($select);
echo json_encode($row);
?>
JS example (fetches the PHP above) *note: this uses jQuery 3.4.1
$(document).ready(function() {
$.ajax({
url:"myserverfile.php",
method:"POST",
dataType:"json",
success:function(response) { // Doesn't have to be called response, can be anything
var a=(response[0]['indexone']); // A name of an index from the sql row you are retrieving
var b=(response[0]['indextwo']); // A name of an index from the sql row you are retrieving
var c=(response[0]['indexthree']); // A name of an index from the sql row you are retrieving
// Check to see values
console.log(a);
console.log(b);
console.log(c);
}
});
});
Tested on a working server with live database.

how to display in json format using php

using php database connection i want to display data in json format which data are fatched from database(MySql),but i can't displaying in json format. http://takeyourtime.16mb.com/fatchData.php
$con = mysqli_connect($host, $username, $pwd, $db) or die('Unable to connect');
if (mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$name = $_POST['Query'];
$sql = "SELECT * FROM playerstb";
$query = mysqli_query($con,$sql);
if ($query)
{
$rows = array();
while ($r = mysql_fetch_assoc($query)) {
$rows['root_name'] = $r;
}
}
echo json_encode($rows);
mysqli_close($con);
Just use json_encode. BTW, your script has an syntax error in the ending if block:
if($query){
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows['root_name'][] = $r; // probably must be an array
}
echo json_encode($rows);
}else{
/*
This will show up when you have a query error
nothing to do with the results found.
I would consider changing the message below
*/
echo('Not Found');
}
inside your while loop you dont save all results you each one writen over the before one
you have to store it in array like note this ([])*
while($r = mysql_fetch_assoc($query)) {
$root_names[] = $r;
}
echo json_encode(['root_name'=>$root_names]);
You have to store first your result in array then after that create an array name your desire key ($array["name"])
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$name=$_POST['Query'];
$sql="SELECT * FROM playerstb";
$query=mysqli_query($con,$sql);
if($query)
{
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
$data["data"]=$rows;
echo json_encode($data);
}
}else
{
echo('Not Found ');
}
mysqli_close($con);
?>

JSON Array of objects with MySql

i am trying to get this output from a database of countries. i had use the mysqli_fetch_object() function but it does not work with me
"countries":[{"countryname":"India","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/india.png","language":"Hindi","capital":"New Delhi","currency":{"code":"INR","currencyname":"Rupee"}},{"countryname":"Pakistan","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/pakistan.png","language":"Urdu","capital":"Islamabad","currency":{"code":"PKR","currencyname":"Pakistani Rupee"}}]}
and i am use this php script
<?php
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
{
die ("Erro in connection" . mysqli_connect_error);
}
else{ $encode = array();
$sql="select * from country ";
$res=mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
//$temp_array[]=$row;
$encode=$row;
}
//echo json_encode($temp_array);
echo json_encode($encode);
}
else
{
echo " 0 Rows";
}
}
?>
if anybody can help me ?
Your code should be something like below;
<?PHP
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
die ("Error in connection" . mysqli_connect_error);
else{
$encode = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
$encode[]=$row;
}
}
echo json_encode($encode);
}
?>
You do not need to write down 0 rows because you are returning a json object which has an array so when you check result.length it tells you the row count.
As an advice you may use something like below;
<?php
require 'config.php';
$con = mysqli_connect($servername,$username,$password,$db);
$resultArray = array();
$resultArray["error"] = true; //That will tell your javascript client if any error exits.
$resultArray["errorMessage"] = ""; //We will set this value if any error exits;
if(!$con)
{
$resultArray["error"] = true;
$resultArray["errorMessage"] = "Error in connection" . mysqli_connect_error();
}
else{
$resultArray["error"] = false;
$itemCollection = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
while($row = mysqli_fetch_object($res))
$itemCollection[]=$row;
$resultArray["itemCollection"] = $itemCollection;
}
echo json_encode($resultArray);
?>
In my sample you are going to get a json result something like below;
{"error":true,"errorMessage":"ErrorMessageIfExists","itemCollection":[yourObject,yourObject]}
Hope this helps you.

Loop an If Statement for each row in Sql table

I am trying to make an If statement in PHP loop for each row in an Sql table. I think I'm almost there but there is a syntax error that I cant quite figure out. Heres what i've got so far:
$mysqli = new mysqli("localhost", "root", "usbw", "favourites");
// check connection
if ($mysqli->connect_errno) {
die("Connect failed: ".$mysqli->connect_error);
}
$query = "SELECT * FROM defaultTiles";
$result = $mysqli->query($query);
while($row = $result->fetch_array()){
echo "<?php if ($tile_name === '$row[name]'){
$tile_colour = '$row[colour]';
$img_url = '$row[img_url]';
$link_url = '$row[link_url]';
} ?>";
}
Replace
while($row = $result->fetch_array()){
echo "<?php if ($tile_name === '$row[name]'){
$tile_colour = '$row[colour]';
$img_url = '$row[img_url]';
$link_url = '$row[link_url]';
} ?>";
}
with
while($row = $result->fetch_array()){
if ($tile_name === $row['name']){
$tile_colour = $row['colour'];
$img_url = $row['img_url'];
$link_url = $row['link_url'];
}
}
as, when you put an echo in front of the if statement, it just prints the statement inside the echo.

Connect php with server

I am connecting to server with help of php for an android application.
Name of Database in phpmyadmin is "student" , name of table is "data" and fields are "Name" and "EmpId"
This is what I coded n php and getting the error on the "$output" part as undefined variable
Here is the code:
<?php
$connection = connectionserver ();
function connectionserver (){
$con = mysql_connect("localhost", "root", "") or die ("connection not found");
if($con)
echo "Connection Created" ,"<br>";
$database = mysql_select_db ("student1", $con);
if($database) echo "Database Connected" , "<br>";
return $con;
}
$result = mysql_query("select * from data");
while ($row = mysql_fetch_assoc($result))
{
$output [] = $row;
}
print json_encode($output);
mysql_close($connection);
?>
declare $output as array before the while
$output = array();
$undefined_array[] = 'something' will not trigger an E_NOTICE error. However it is good practice to initialize the variable.
The error comes from the line with json_encode, most likely because your query didn't return any result, didnt get into the while loop, thus $output[] was never executed.
You may try this:
<?php
$connection = connectionserver ();
function connectionserver (){
$con = #mysql_connect("localhost","root","");
if(!$con) die("Can't connect!!");
$var2 = #mysql_select_db("student1",$con);
if(!$var2)
die("<br>"."can't select dataBase");
$result = mysql_query("select * from data");
while ($row = mysql_fetch_assoc($result))
{
$output[] = $row;
}
print json_encode($output);
mysql_close($con);
}
?>
Try this,
echo connectionserver();
function connectionserver (){
$con = mysql_connect("localhost", "root", "") or die ("connection not found");
$database = mysql_select_db ("student1", $con);
$result = mysql_query("select * from data") or die(mysql_error());
$output = array();
while ($row = mysql_fetch_assoc($result))
{
$output[] = $row;
}
mysql_close($con);
return json_encode($output);
}

Categories