Pass variables in url to get specific JSON output - php

I'm attempting to create an api, I'm currently trying to append variables to the url to get specific data back in the JSON output.. I can currently display all contents of a table. Any advice would be appreciated.. Please see code below...
$connection = #mysqli_connect($server, $user, $password, $bd);
if( ! $connection ) die( "Error ".mysqli_connect_error() );
$sql = "SELECT * FROM posts";
$result = mysqli_query($connection, $sql);
$array_post = array();
while($data = mysqli_fetch_assoc($result)){
$array_post[] = $data;
}
echo json_encode($array_post);

You probably mean an api response after a POST or GET Request? Am I right?
If it is, then you can do this...
$response = $array_post;
http_response_code(200);
print json_encode($response);
You need a stream to output the JSON data, you can set the HTTP status code by http_response_code($code) function and then print the response.
There are packages out there that could handle api request and response.
I suggest you take a look about Curl or much better the GuzzleHttp.
Hope it helps.

You can store particular values return from SQL query to array keys like this
while($data = mysqli_fetch_assoc($result)){
$array_post['key2'][] = $data['key2'];
$array_post['key2'][] = $data['key2'];
}
echo json_encode($array_post);
Use only those values which you required to pass in URL.
If you need all the records then your code is right.
If you are thinking about some records then change your query to
like SELECT field1,field2 FROM table_name.
because some times it will affect performance of executing SQL query.

Related

Using passport token in API select query

I am building an app using ExpressJS and NodeJS, and database for this application will be postgresql. Right now i'm actually stack on API part.
So i made a simple API in PHP, please look at the code below
<?php
// Create connection
$con=new PDO('pgsql:host=localhost;port=5432;dbname=name;user=postgres;password=password');
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT totalscore, datestamp_app FROM tests";
// Check if there are results
//if (
$result = $con->query($sql);
//{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
//}
// Close connections
//pdo_close($con);
?>
So i'm able get a JSON with a data from SQL SELECT query
Perfect.
From the other site i'm able on my application get token for a users using passportJS (Google, Facebook, local tokens)
But my question is (and i'm really try to solve it last week) that should i do with this token regards Select query, as right now then API.php execute i get all data from tests table, put my goal is to get data only for concrete user with their token.
Any help will be really appreciated, thank you in advance.

How to retrieve data from SQL Server?

I was wondering why my query is returning null when I know there is data there.
my query is as follows:
if (isset($_POST['noteid']))
{
$showNoteInfo = "SELECT Note FROM Notes WHERE NoteID = 2";
$showNotes = sqlsrv_query($conn, $showNoteInfo);
var_dump($showNotes);
}
I have tested $_POST['noteid'] and that displays an ID no problem, in theory this id will replace where I have the number 2 in my query.
However I know in my table in the Notes table where NoteID = 2 the text should be like this
However var_dump displays "resource(7) of type (SQL Server Statement)"
And I have also tried a different method of displaying it and that returned as the query expected resource and was given NULL, so why is this query not getting any results?
My connection details are in an include at the top of the page and are like this: http://pastebin.com/qz3tScdW
If you need anything else please ask.
Underlying question, why is my Query returning NULL when I know theres data there?
You never actually try to retrieve your data. sqlsrv_query performs the database query, but it doesn't get the data. You need to use sqlsrv_fetch_array (or sqlsrv_fetch_object) for that:
$stmt = sqlsrv_query($conn, $showNoteInfo);
if (sqlsrv_has_rows($stmt)) {
$data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
var_dump($data['Note']);
} else {
echo "No data found";
}

Get data from MYSQL using PHP returns no results

So I am using this tutorial: https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/ to try and get data from my local MYSQL server (using Wamp64). I had the undefined index error at first, which I fixed using the isset() statement.
But now it just returns:
{"result":[]}
I have, however, a lot of data in the set column of that database.
Here is the code:
<?php
//Getting the requested klas
$klas = isset($_GET['klas']) ? $_GET['klas'] : '';
//Importing database
require_once('dbConnect.php');
//Creating SQL query with where clause to get a specific klas
$sql = "SELECT * FROM lessen WHERE klas='$klas'";
//Getting result
$r = mysqli_query($con,$sql);
//Pushing result to an array
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
//Displaying the array in JSON format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I tried out the
SELECT * FROM lessen WHERE klas='$klas'
statement in my database and it seems to return the correct data.
Any idea what is causing this?
Thanks in advance!
Point 1 is:
isset function only checks if klas is set in the $_GET global array. So if somehow $klas is blank - your query will return empty (without giving error).
So please check values in the $_GET and possibly from where it is accessed. Or you can add condition to avoid empty query like --
if (!empty($_GET['klas'])) {
// rest of the code block upto return
Point 2 is:
You have mentioned if you echo the sql it returns
SELECT * FROM lessen WHERE klas=''{"result":[]}
Here the second part (the JSON) is from echoing the result at the end of your code. So for the first part (i.e. echoing $sql) we see that klas=''. That actually goes to the Point 1 as mentioned above.
So finally you have to check why the value at $_GET is showing blank. That will solve your problem.
UPDATE:
From #GeeSplit's comment For the request
"GET /JSON-parsing/getKlas.php?=3ECA"
There will be nothing in $_GET['klas'] cause the querystring in the url doesn't contain any key.
So either you have to change the source from where the file is called. Or you can change how you are getting the value of klas.
Example:
$tmpKlas = $_SERVER['QUERY_STRING'];
$klas = ltrim($tmpKlas, '=');
Rest of your code will work.
Use this code
<?php
$klas ='';
if(isset($_GET['klas']) && !empty($_GET['klas']))
{
$klas = $_GET['klas'];
require_once('dbConnect.php');
$sql = 'SELECT * FROM lessen WHERE klas="'.$klas.'"';
$r = mysqli_query($con,$sql);
$result = array();
while ($row = mysqli_fetch_array($r)) {
array_push($result,array(
"id"=>$row['id'],
"klas"=>$row['klas'],
"dag"=>$row['dag'],
"lesuur"=>$row['lesuur'],
"les"=>$row['les'],
"lokaal"=>$row['lokaal']
));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
}
?>

How to make query into arrays?

I'm using this code to gather information from database
$webdata = "SELECT * FROM `settings`";
if (!$web_data = $db_connect->query($webdata)) {
die('Oops, something went wrong during loading data! Error x010');
}
but now I would liek to display it like arrays so taht I can just simply use this code:
<?php echo $web_data['web_name']; ?
to display the information
Since you tagged this mysqli, you need to fetch the results into an array.
You can do so with mysqli's fetch_assoc():
$webdata = "SELECT * FROM `settings`";
if (!$web_data = $db_connect->query($webdata)) {
die('Oops, something went wrong during loading data! Error x010');
}
while ($row = $web_data->fetch_assoc()) {
echo $row['web_name'];
}
Echo will just send Array text in response.
To send an array use print_r function.

PHP script for getting data from mysql only getting a portion of the values

I'm trying to get data from a mysql table and send it via a php script as a json string so it later can be used by for example ios apps.
The code i have so far is:
<?php
$con = mysql_connect("xxx", "xxx", "xxx");
mysql_select_db("FreeSir_MarinaLaroverket") or die("Unable to select database");
$arr = array();
$rs = mysql_query("SELECT * FROM Nyheter");
while($obj = mysql_fetch_assoc($rs))
{
$arr[] = $obj;
}
echo json_encode($arr);
?>
But when i use the script i get the following:
[{"Index":"1","Title":null,"News":null,"Date":"11\/1"},{"Index":"2","Title":"Andra nyheten","News":null,"Date":"22\/2"}]
As you might see there, i have some null values that pops up there from nowhere. I've doublechecked that i have the correct values inserted and all, but it still just gives me null.
I would appreciate it if anyone of you could see what is making this code not giving me all the values i want.
Best Regards
FreeSirenety
If your var_dump($arr) statement displays the correct data, so you probably have a problem with the JSON representation. Check the manual for json_encode(), and look for the $options parameter.

Categories