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

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.

Related

PHP SQL server query

I'm running a query to get the contents for a web slider.
$serverName = "livedata";
$connectionInfo = array( "Database"=>"DB", "UID"=>"User", "PWD"=>"PWD" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Sliders.DisplayFrom, Sliders.DisplayUntil, Sliders.Sort, Sliders.Image, Sliders.Link, Sliders.Target FROM Sliders WHERE (((Sliders.DisplayFrom)<GetDate()) AND ((Sliders.DisplayUntil)>getdate())) ORDER BY Sliders.sort;";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_query($conn, $sql);
$maxx = 0;
while($row = sqlsrv_fetch_array($result)) {
$maxx++;
}
while($row = sqlsrv_fetch_array($result)) {
echo “<br>” . $row[‘Image’];
}
The second loop does not output any results. why? Is it because $row is already at the end? If so, how do I move first like in ASP without having to create $result2 and $row2, 3, 4, 5, ...
Would it be better to use for loops like in vb.net?
for ($i = 0; $i <= $maxx; $i++){
}
But then How do I specify the output if I have no $row?
and if I only wanted to output the first row like I do in vb.net, how would I write the following in PHP?
dsqueryResults.tables(0).rows(0).item("Image");
would I still use a while loop and have a variable inside the loop to hold the row number and only output if row = 0?
$WhichRow = 0;
while($row2 = sqlsrv_fetch_array($result2)) {
if ($whichRow == 0){
echo “<br>” . $row2[‘Image’];
}
$WhichRow++;
}
Use the $max++ counter inside the while loop if you really want to use that for other purposes.
If you just want a count then run a count query on MySQL or do an array count of returned result.
If you just want to print 1 row use
LIMIT 0,1
at the end of your query as there's no point in fetching all rows and waste resources.
Based on additional comments you can try this to get your current row number.
$result = sqlsrv_query($conn, $sql);
$rownumber = 0;
while($row = sqlsrv_fetch_array($result)) {
$rownumber = $rownumber + 1;//Your current row number.
echo “<br>” . $row[‘Image’];
}

Seperating retrieved data from MYSQL for Json (Preparing for API C#)

I'm trying to prepare data as Json for my API, this is the code i currently have:
if(isset($_GET)) {
include('db.php');
$result = mysqli_query(
$con,
"SELECT * FROM `vragen`");
while($row = mysqli_fetch_assoc($result)) {
$vraag_ID = $row['vraag_ID'];
$vraagnummer = $row['vraagnummer'];
$vraag = $row['vraag'];
response($vraag_ID, $vraagnummer, $vraag);
}
}
function response($vraag_ID, $vraagnummer, $vraag)
{
$response['vraag_ID'] = $vraag_ID;
$response['vraagnummer'] = $vraagnummer;
$response['vraag'] = $vraag;
$response = [$response];
$json_response = json_encode($response);
echo $json_response;
}
Which outputs this Data:
[{"vraag_ID":"1","vraagnummer":"1","vraag":"Vraag1Vraag1Vraag1Vraag1"}][{"vraag_ID":"2","vraagnummer":"2","vraag":"Vraag2Vraag2Vraag2Vraag2"}][{"vraag_ID":"3","vraagnummer":"3","vraag":"Vraag3Vraag3Vraag3Vraag3"}][{"vraag_ID":"4","vraagnummer":"4","vraag":"Vraag4Vraag4Vraag4Vraag4"}][{"vraag_ID":"5","vraagnummer":"5","vraag":"Vraag5Vraag5Vraag5Vraag5"}]
Obviously this is isn't "Json ready" yet and outputs it just as plain text.
Thanks in advance.
You don't need such a function, you are overcomplicating the task. Just build your array directly into the while loop:
<?php
if (isset($_GET)) {
include('db.php');
$result = mysqli_query(
$con,
"SELECT * FROM `vragen`");
$response = [];
while ($row = mysqli_fetch_assoc($result)) {
$response[] = $row;
}
echo json_encode($response);
}
?>
And within your SELECT you can specify upfont which fields to be included.

Pull data from mssql to array - PHP

I pull data from the mssql database. I want to assign the data I have captured as an array. So I want to assign more than one table value to the result. Currently, it only assigns 1 value. When I make $ results [], I can't print. I converted it to an array so I can assign more than one data, but it doesn't work.
<?php
...
$conn = sqlsrv_connect( $serverName, $connectionInfo );
$sql = "...";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array($stmt) ) {
$destekCevap = $row['destekcevap_..'];
$destekCevapFoto = $row['destekcevap_...'];
$results = Array("destekcevap_.." => $destekCevap, "destekCevapFoto" => $destekCevapFoto);
}
echo json_encode($results);
sqlsrv_free_stmt($stmt);
?>
Initialize the array above the while-loop and assign new values in the loop like this:
$results = array();
while( $row = sqlsrv_fetch_array($stmt) ) {
$destekCevap = $row['destekcevap_..'];
$destekCevapFoto = $row['destekcevap_...'];
$results[] = "your values";
}
Cheers,
Niklas

sql server data to json using php

My json code doesn't display anything, I have already tried many codes but nothing has helped.
include('connect.php');
$sql = "SELECT * FROM items";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) //this loop is working
{
echo $row['item_id'].", ".$row['item_name'].", ".$row['Barcode']."<br>";
}
$json = array();
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$json[] = $row;
}
} while ( sqlsrv_next_result($stmt) );
echo json_encode($json); //empty?!
sqlsrv_free_stmt( $stmt);
There are numerous likely issues with this:
1) Have you checked your query actually returns rows?
2) You're looping your data twice (two while( $row = sqlsrv_fetch_array... loops) which is not useful or efficient.
3) the do...while ( sqlsrv_next_result($stmt) ); clause should be unnecessary as well, as fetch_array will know when it's got to the end of the data, and you've only got one resultset, so you don't need to move between them
4) you're echoing raw data as well as JSON, so if you make an ajax call to this script it'll fail because the response will partly contain non-JSON data
I think this will be sufficient to get you some sensible data:
include('connect.php');
$sql = "SELECT * FROM items";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$json[] = $row;
}
echo json_encode($json);
If THIS works:
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) //this loop is working
{
echo $row['item_id'].", ".$row['item_name'].", ".$row['Barcode']."<br>";
}
the rest must work too.
As ADyson says:
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$json[] = $row;
}
echo json_encode($json);
for double check add your echo in this code, like this:
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
$json = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
echo $row['item_id'].", ".$row['item_name'].", ".$row['Barcode']."<br>";
$json[] = $row;
}
echo json_encode($json);
If this code works, accept the ADyson answer
here is a way to solve the issue .Hoping your query is well written.
$dataFinal= array();//final variable that will contain total array for json
for($k=0;$k<count(variable_that_contents_the_resutl_array_query);$k++){
$ligne = array("item_id"=> $row['item_id'],
"item_name"=>$row['item_name'],"Barcode"=> $row['Barcode']);
array_push($dataFinal, $ligne);//add line in array datafinal
}//end for loop
$result = array($dataFinal);
$response = new Response(json_encode($dataFinal));
$response->headers->set('Content-Type', 'application/json');
return $response;

how to receive data from a php file into angularjs code

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.

Categories