sql server data to json using php - 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;

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.

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

multiple values an array php - Mssql

I'm pulling data from mssql. The data I have captured is more than one. It only records one data to Array. As you can see in the photo, there is more than one content with soru_tur = 1. How can I save soru_baslik and soru_icerik data to array? I show the data I have captured in my swift application. A database screenshot has been added with the var_dump output.
" json["soru_baslik"] " >> I want to print it out from swift. The screenshot of the output is as follows
<?php
...
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$json = file_get_contents('php://input');
$sql = "SELECT soru_baslik, soru_icerik FROM ... WHERE soru_tur = 1";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$soruArray = array();
$soruicerikArray = array();
$array = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results[] = Array("soru_baslik" => $row['soru_baslik'], "soru_icerik" => $row['soru_icerik']);
}
//var_dump($array);
echo '<pre>'; print_r($results); echo '</pre>';
sqlsrv_free_stmt( $stmt);
?>
If I understand your question correctly, one issue with your code is that you are initializing the $result variable on each iteration. You need to initialize this variable once and then append items on each iteration. You may try with the following approaches:
Example 1 (fetch only two specific columns):
<?php
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$json = file_get_contents('php://input');
$sql = "SELECT soru_baslik, soru_icerik FROM ... WHERE soru_no = 1";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$results = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results[] = array(
"..._baslik" => $row['..._baslik'],
"s..._icerik" => $row['..._icerik']
);
}
header("Content-Type: application/json");
echo json_encode($results);
sqlsrv_free_stmt( $stmt);
?>
Example 2 (fetch all columns):
<?php
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$json = file_get_contents('php://input');
$sql = "SELECT soru_baslik, soru_icerik FROM ... WHERE soru_no = 1";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$results = array();
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$a = array();
foreach($row as $column => $value) {
$a[$column] = $value;
}
$results[] = $a;
}
header("Content-Type: application/json");
echo json_encode($results);
sqlsrv_free_stmt( $stmt);
?>

SQLSRV doesn't fetch all rows

I'm using the sqlsrv extension for php and have a problem with fetching the rows from a simple query.
My query is a select which should return 133228 rows but when trying to display the rows I get only 15.
I've searched for an answer but couldn't find a solution and this is my first time using this extension. I've found an answer to a previous question about the same problem but in that case the problem was double calling of sqlsrv_fetch_array, which I don't have for sure.
Here is my query:
$sql = 'select * from ViewProduct';
$params = array();
$options = array('Scrollable' => SQLSRV_CURSOR_KEYSET);
$stmt = sqlsrv_query($dbRemote, $sql, $params, $options);
$count = sqlsrv_num_rows($stmt);
if ($count === false)
echo "Error in retrieveing row count.";
else
echo $count;
//$rows = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
print_r($row);
echo "<br>";
//$rows[] = $row;
}
As I said the above query returns 15 when should be 133228 rows.
What am I missing?
Thank you in advance.
i have same problem,
this is my solution for this
$data = [];
$result_num = false;
// get rows num if have any
$result_count_res = sqlsrv_query(
$conn,
$query,
[],
[ "Scrollable" => SQLSRV_CURSOR_KEYSET ]
);
if( $result_count_res === false) {
echo "Row count false";
}else{
// set row num
$result_num = sqlsrv_num_rows( $result_count_res );
}
if($result_num){
// run another query to retrive results
$result_res = sqlsrv_query(
$conn,
$query,
[],
[ "Scrollable" => SQLSRV_CURSOR_FORWARD ]
);
if( $result_res === false) {
// get errors from query
die( print_r( sqlsrv_errors(), true) );
}else{
// run through "for" loop to retrive all results
for($i = 0; $i < $result_num; $i++){
$data[] = sqlsrv_fetch_array( $result_res, SQLSRV_FETCH_ASSOC);
}
}
sqlsrv_free_stmt( $result_res );
}else{
echo "Row count false";
}
echo '<pre>';
var_dump($data);
echo '</pre>';

Assign values from an array to specific PHP variables

I am trying to use PHP to select values from a SQL Server DB and assign values to specific parameters.
The table I am selecting from looks like this:
**ColumnName1 ColumnName2**
DataRow1Col1, DataRow1Col2
DataRow2Col1, DataRow2Col2
DataRow3Col1, DataRow3Col2
DataRow4Col1, DataRow4Col2
I am trying to create a variable that will be equal to DataRow3Col2 which always has a ColumnName1 = DataRow3Col1.
Is this possible?
Here is what I have so far:
$sql = "SELECT * FROM Table where id = {$ID}";
$stmt = sqlsrv_query( $trpConn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$data = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$data[] = $row;
}
sqlsrv_free_stmt( $stmt);
Thank you
$sql = "SELECT * FROM Table where id = {$ID}";
$stmt = sqlsrv_query( $trpConn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$data = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$data[$row['ColumnName1']] = $row['ColumnName2'];
}
sqlsrv_free_stmt( $stmt);
extract($data);
echo $DataRow1Col1;
// The Output is: DataRow1Col2

Categories