Using passport token in API select query - php

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.

Related

How to alter PHP information coming from mySQL before JSON_encode?

I'm have a live website that uses PHP and a mySQL database. I'm looking to use d3 to create a few visualizations. But I don't know how to alter the data as it is stored in the SQL database before directly encoding it in a JSON for d3. My PHP:
$activity_array = $array;
while ($activity = mysqli_fetch_assoc($get_all_activities)) {
// $user_name = find_user_by_id($activity['user_id']);
// echo $user_name['last_name'];
$activity_array[] = $activity;
}
echo json_encode($activity_array);
However, due to how my mysql database is set up, users are set up as numbers, so that what I get back in the JSON looks like:
[{"id":"93","date":"2020-05-01","user_id":"37","user_notes":"This user has blah blah."},...]
When I use this JSON to generate a graph in d3, I want it to show the actual user's name, not "37". In the PHP code above I commented out the query I have to get the user's name from their user_id, but then I have no idea how to get that into my JSON.
Thanks for the help!
You just need to modify the appropriate entry in the $activity array with the username retrieved by the second query:
$activity_array = $array;
while ($activity = mysqli_fetch_assoc($get_all_activities)) {
$user_name = find_user_by_id($activity['user_id']);
$activity['user_id'] = $user_name['last_name'];
$activity_array[] = $activity;
}
echo json_encode($activity_array);
It would however probably be easier to modify the $get_all_activities query to JOIN to the users table and fetch the username in that query directly.

Json array don't show me 5 or more Rows on PHP Script to a SQL Database

When I'm trying to perform basic CRUD operation on my database, but here when I tried to get a single row from my database whit a php script, I see the correct data from my database, but when I'm put more rows on de data base, and I tried to get the data, it never appears.
I'm using this PHP Script
<?php
//Importing Database Script
require_once('Connectdb.php');
//Creating sql query
$sql = "SELECT * FROM ensaladas ";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_assoc($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"ensid"=>$row['ensid'],
"nombre"=>$row['nombre'],
"precio"=>$row['precio'],
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
And gives me the next result:
I use this when the table has 2 rows, and when I put another rows, the code stop Working. The table of the database has 3 fields: ensid,nombre,precio. As you can see here:
PD: I'm using this script to get the data on an Android APP
Error checking
Do some error checking on your part. You can also try to run the query at the back-end of your system (PhpMyAdmin).
Fetching data
Since you are using mysqli_* API already, try using prepared statement instead:
$stmt = $con->prepare("SELECT ensid, nombre, precio FROM ensaladas");
$stmt->execute();
$stmt->bind_result($ensid, $nombre, $precio);
while($stmt->fetch()){
array_push($result, array(
"ensid"=>$ensid,
"nombre"=>$nombre,
"precio"=>$precio,
));
}
$stmt->close();
Displaying the data
You can then now display all the data using:
echo json_encode($result);
Or if you want a specific row from the result, you can use an index:
echo json_encode($result[$x]); /* $x REPRESENTS THE INDEX; INTEGER VALUE */
Or get a specific data from a specific row:
echo json_encode($result[$x]['ensid']); /* EITHER ensid, nombre, or precio */
When I took a look into your database selection example(screen), the table name that you are querying is 'bebidas', while in the screenshot of the database you have used 'ensaladad'.
Try to use:
// Creating SQL query
$sql = "SELECT * FROM ensaladas ";
or use:
// looping through all the records fetched
while($row = mysqli_fetch_assoc($r)){
// Pushing name and id in the blank array created
array_push($result,$row));
}

Pass variables in url to get specific JSON output

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.

Get MySQL data and store it to a PHP array based on the data array returned by another MySQL select operation

I am creating an iOS application and I am facing a difficulty with the web service portion, which is written in PHP. What I am trying to achieve is, sending push notification to the devices. I have completed that part. However, I need a mechanism to differentiate between notifications that has been delivered successfully to the phone and that haven't. I use a feedback web-service for this purpose and It is also working. have a MySQL table with the following structure. Based on the status bit of each notification, I collect all the notifications corresponding to each device token, and make it into an array and send it to the device. Here is where I am facing difficulty.
I have two tables.
This table stores the notification ID, device token and status of the notification. By looking at this table, my script can determine whether the notification has been delivered to the particular device or not. My script collects all the notification IDs that has been undelivered to a particular device ID and uses the following apps_notif table to fetch the undelivered notifications. The table structure is as below.
My PHP/MySQL script is as follows.
$fecthnotif=mysqli_query($mysqli,"SELECT notif_id FROM notif_status WHERE notif_status=0 AND dev_token='$device_token'") or die(mysqli_error($mysqli));
$d2=array();
while($row = mysqli_fetch_assoc($fecthnotif)) {
$d2[]=$row;
$json = json_encode($d2);
$arr = json_decode( $json,true);
By this time, I get an array of undelivered notifications as JSON. The result is as follows.
[{"notif_id":"124"},{"notif_id":"129"}]
Now, I loop though the results as follows.
foreach($arr as $item) { //foreach element in $arr
$uses= $item['notif_id']; }
What I am trying to achieve is to take each notif_id from the above result, fetch allthe notification data from the apss-Notif table, make it a single JSON object and return that payload to the app.So that JSON should have all the notification data of all the notifications that were undelivered at the first place.
Inside the foreach loop, I wrote a query loop to store all the pending notifications to array, but it isnt working.
$d=array();
foreach($arr as $item) { //foreach element in $arr
$uses= $item['notif_id']; //etc
//echo $uses;
$sendnotif=mysqli_query($mysqli,"SELECT * FROM apps_notif WHERE notif_id='$uses'") or die(mysqli_error($mysqli));
while($row = mysqli_fetch_assoc($sendnotif)) {
$d[]=$row;
$i++;
}
}
Edit: Basically, what I am trying to achieve is to return rows from the apps_notif table that match the criteria, notif_status=0 (from table notif_status) and dev_token="qwerty" (from apps_notif table)
I can see that two rows are eligible.
Hope it helps
SELECT b.*
FROM notif_status a
INNER JOIN apps_notif b ON a.notif_id = b.notif_id
WHERE notif_status = 0
AND dev_token = '$device_token';
using sub queries,
SELECT *
FROM app_notify
WHERE notify_id IN (SELECT notif_id
FROM notif_status
WHERE notif_status = 0
AND dev_token = '$device_token') ;
See in your table. In table 1 you have notify_id but in table 2 you have date having kind of similar values. Hence if u match table1 notifyId and table2 notifyId you will not get the desired output. First check the proper criteria how the table should be designed.
You can try below PHP code to get the details from 2 table and make JSON object. Not tested query as i don't have respective DB tables.
$query = "SELECT a.* from apps_notif a JOIN notif_status b ON b.notif_id = a.notif_id WHERE b.notif_status=0 AND b.dev_token='$device_token'";
$res = mysqli_query($mysqli,$query);
$d = array();
while ($row = mysqli_fetch_assoc($res)) {
$d[] = $row;
}
$json = json_encode($d);
Hope this helps you.

Android Eclipse How to display specific data from phpMySql database to list view

Hello and good day all,
I have try android eclipse project connect to phpmysql with xampp server. For now i success to get and display all data from mysql database to listview.
But how to only get specific data only. Example :
Name : Class: CodeSubject: SubjectName:
JOHN 2 TBE124
JOHN 2 TKE123
JOHN 2 TZE125
JOHN 2 TDE194
ADAM 2 TAE154
ADAM 2 TQE114
GORGE 2 TGE164
GORGE 2 TCE123
GORGE 2 TBE126
What i want is ListView will show All JOHN data/row/column if spinner select JOHN. If select ADAM then ListView will show All ADAM data/row/column. For my code now, it will show all the data from database. If any have tutorial related please share with me.
I used androidhive tutorial. http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
//here the search value is what you send from the app
if(isset($_GET["matricID"])){
$string_input = $_GET['matricID'];
$result = mysql_query("SELECT * FROM tbl_semester WHERE matricID LIKE '%$matricID%'") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["tbl_semester"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$semester = array();
$semester["pid"] = $row["pid"];
$semester["matricID"] = $row["matricID"];
$semester["code"] = $row["code"];
$semester["course"] = $row["course"];
$semester["point"] = $row["point"];
$semester["crdhour"] = $row["crdhour"];
$semester["grdpoint"] = $row["grdpoint"];
$semester["reattempt"] = $row["reattempt"];
$semester["grd"] = $row["grd"];
// push single product into final response array
array_push($response["tbl_semester"], $semester);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
}
?>
This can be done in two ways:
By Querying mysql database on each spinner selection.
on every selection of the spinner send the request to the database.
server will return a JSON object, parse that json object and populate the listview
by this way app load will be less bu the server load will be a bit more.
By handling all stuff in java file only
make a JSON object corresponding to the key="name": value={all fields related to the name}
make a logic for looking into this JSON object on the basis of the name for each spinner selection and populate the list view with the value fields corresponding to the key name
but this will load the app with the data which you may not be needing, because all the names will be loaded with their properties in the JSON object
I suggest you to implement the First method.
You need to write a webservice which will get the data from your mysql database and send it to your android app.
Write a php script on your server, get the data, encode it inside a JSON object and send it to your app.
The tutorial you have quoted well describes the way to do it. You can follow the same.
To handle the second part of your question, send the item selected on the spinner to the server via a POST or a GET. Create a query to retrieve the rows using the data sent to the server. Send the retrieved data back to the app the similar way you have done it earlier. Then populate the data received in your ListView.
The same tutorial shows this demonstration as well.
Hope it helps.
You sample php at the server could be something like this
//here the search value is what you send from the app
if(isset($_POST["searchvalue"])){
$string_input = $_POST['searchvalue'];
$result = mysql_query("SELECT * FROM TABLENAME WHERE NAME_COLUMN LIKE '%$string_input%'") or die(mysql_error());

Categories