How to use an API in my program?

As Ernie mentioned a while ago, your API isn’t returning valid JSON. You need to use the while($row = mysqli_fetch_array($result)) loop to build the array you want to return, then encode it all at once rather than piece by piece. Something like:

$output = [];
while ($row = mysqli_fetch_array($result)) {
    $output[] = [
        'material_code' => $row['material_code'],
        'importation_quantity' => $row['importation_quantity']
    ];
}

echo json_encode($output);
    
1 Like

Thanks again,
The latest output is this output:

So, It is Ok
I’m deeply grateful for your time and consideration.

Great! Glad we could help. It was a group effort. All the pieces solved now! Ha, now you can get to really finishing up your project!

1 Like

Thanks for your kind replies,
If I want to write an API which must be dynamic in a grid, how to do that?
Let me explain in more details:
At the previous API, clients should enter a code, and then in the browsers, they can see importation_quantity based on that code.
But now, there is a grid with some rows(client side), and in each row, the materials code are written there by clients or automatically.
So, I need to write an API to return importation_quantity based on that material_code which must be related to that row.
For example in the first row, material_code maybe would be 1, and in the second row, it maybe would be 2,… , And So, the API must be responsible to return importation_quantity based on each material_code.
How to do that?
I would be very grateful. if you could consider some time to support me.
Thanks in advance.

Well, to handle something like that, you have two choices. First, you could create an array of all the codes you want to pull from the api and send it in the query when you load the data. That can get complicated. Passing a lot of numbers thru GET to your api can be hard to process.

The second way would be easier. You would need to keep an array in the calling page and just pass an array with ease thru the $_SESSION[] array. Just save it in like you would any other data. Then, when the page is loaded loop thru the array and display all the data by pulling it from the api.

Not sure if you understand that. I will explain a little further. You create an array for the code numbers. Let’s call it $code_array. Each time the user requests to add a code number to add a row, you just add that code to the $code_array. And, of course, save it to the $_SESSION array as you would with any other saved data. Like this: $_SESSION[“codes”]=$code_array; Easy. Then, each time you load the page, you just loop thru the array to call the api and display the needed rows. Since the SESSION array is available on the server, you can just refresh the page and have the array passed to the API for displaying it.

Another way you could process this is to just not use the api calls. Originally, when you started this, we assumed you have an API that was already written and you just needed to call it in your own page. Normally, if you have that code already working, you can just include it into your file instead of having to call out to it. But, either way it can be done. ANYTHING can be done in code if you take the time to learn how to do it. Good luck!

1 Like

Good information thanks for sharing
vmware

1 Like

Thanks for getting back to me,
Let me to share the latest file with you. I wrote the API with help of you like this:

header(“Content-Type:application/json”);
if (isset($_GET[‘material_code’]) && $_GET[‘material_code’]!="") {
include(‘db.php’);
$material_code = $_GET[‘material_code’];
$query = “select material_code,sum(importation_quantity) as sum_importation_quantity from stock_information where material_code=$material_code”;
$result = mysqli_query($con, $query);
mysqli_query($con, “SET NAMES utf8”);
$output = [];
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)) {
$output[] = [
‘material_code’ => $row[‘material_code’],
‘importation_quantity’ => $row[‘sum_importation_quantity’]
];

}
echo json_encode($output);
}else{
response(NULL, NULL, 200,“No Record Found”);
}
}else{
response(NULL, NULL, 400,“Invalid Request”);
}

And, i need to use the API in other program. So, I write something like that

$pmServer = “http://localhost:1367/rest-api2/api-alis.php?material_code=”;
$lenGrid = count(@=planning_evaluation);
for($x = 1; $x <= $lenGrid;$x++ ) {
@=planning_evaluation[$x][‘material_code’] = $material_code;
@=planning_evaluation[$x][‘remainder’] = $remainder;
}

$url = $pmServer.$material_code;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$result = json_decode($response);
foreach ($result as $results) {
{$results->material_code} : {$results->importation_quantity} ;
}
$quantity1 = $results->material_code;
$quantity2 = $results->importation_quantity;
@@remainder = $quantity2;

I see this error: Invalid argument supplied for foreach()

Can you please help me to correct it, you mentioned that I should add $code_array and save it to the $_SESSION array.
$_SESSION[“codes”]=$code_array;
Thanks in advance.

Well, I do not understand all the @'s in your code. That suppresses errors and you should look at all errors while you develop a system. In some cases for live sites you can do this. But, even on live sites, you should add error handling instead of just suppressing errors.

Now, if you use json_decode() as-is, it creates an object, not a standard array. Therefore, you would need to parse the object. But, to get around that, you can just create an array by adding an option in it like this:

$result = json_decode($response, true);

This will create a standard array instead of an object. Then, you can use a foreach to parse it.

1 Like

Thank you very much, I really appreciate you.
In that application, I need to use @ it. It is a grid.
What about the array code and session which you mentioned in your previous post.
Where should I put those?
Thanks again

Well, Mohamad, to answer that question, I would have to ask a question.

How secure does this system need to be. I will explain a little. If you have a webpage, which you are calling an API, it can be found by hackers or just regular people. If the page pulls data from a database, anyone who finds that page can enter the code by just going to the page.
http://localhost:1367/rest-api2/api-alis.php?material_code=1234;
And, that data would display on the page. So, it can be hacked. They could get all of your data for every material_code by just changing the material_code number. But, if this is handled just locally on your own machines, it is not an issue.
Also, you acquire the number from this:
$material_code = $_GET[‘material_code’];
So, the data returned from the page is NOT protected from hackers. It can include a command that will erase your entire database. You need to at least filter the input like this:
$material_code = filter_input(INPUT_GET, "material_code"];
This will remove any programming that is inside the GET results…

Now, to pass the data directly, you can not use the $_SESSION array if the data is pulled from another page since the other page may not be on the same server. Do you understand that difference.

Therefore, to really answer your question, I need to know how you plan to use this API system. Are you planning on creating the API on a website and then call it from other computers to allow to view the data elsewhere such as on a phone or iPad or other remote computer? If so, you need to do it that way, you can force the connection to log in. Since you use cURL, you can have that log into the api page. Fairly easy. But, adds more work.

If the system is just local, meaning if it is on a server you or your company will be using and no outside people can access it, then security is not important. At the beginning of this post, you mentioned the API part and second part, but, you did not mention how they will link together. Please explain how you will use these two program you showed us and then we can suggest the best way to handle this one.

1 Like

Great information,
Well, in this part, I want to have a good practice about API.
But in reality, an external warehouse apolication gives me a web service/API for calling it in the other application which is PHP based.
So, those application are not in the internet. However, maybe for some users the accessibilty will be opened but by Firewall.
But, I guess security is important.
Anyway, There are some communications between 2 applications. So, I need to write API and also call API.
And again thanks for your precious time and consideration.

Okay, so, in your post, you said security is important and two separate applications.
In that case, you would need to pass the material codes or other data without it being seen publicly.
You can use a POST system instead of GET’s. This will hide the requested numbers from webpages.
Since this is two different applications, it is more secure to require a login from the remote system to the
server system. The first computer, the one with the API would be the server and whoever connects into it,
would be the remote unit.

To do this, you have two options. Set up the server system to use HTTPS instead of HTTP. Then, you can require a login which is easy to add. OR, you have to create a way to secure it yourself. Often, you can set up a login system on the server so that a page can not be accessed unless logged in. cURL will let you handle login’s. Or, you can secure it with special passwords or even IP address checks.

If this is for a business manufacturing plant, I would assume it would have a server with all the data on it which can be connected to remotely. In which case, you would have an IP address or just a URL to let you connect to the server. Since PHP runs only on the server, you can not just use a simple two-file connection as we have been talking about. Unless you have two servers, both running PHP.

You might just want to create a remote access webpage instead. That would be just a web page on the server with a login system and that would give access to the data as needed. This might be simpler for you to create. So, you mentioned running a PHP page to call another one thru a firewall. That is very easy to do, but, it does require that the one on this side of the firewall to be a server so it can run PHP. Or, the same thing can be done with a webpage on the server that can be called from the remote one.

I really have not given you an answer, just tried to explain what might be needed to get this working for you. Do you understand this part so far? You should think out how you plan this to work. Then we can plan a way for you to do it all.

1 Like

Dear Ernie, thanks for your kind reply,
There is a login page from the client side. I mean, clients have to login to access the form to be called API.

Well, in that case, all you need to do is to check in the client side that a user is logged in before calling the API form.

So, with a log in, you do not have to worry about someone hacking into it. Just check at the top of the page that calls the API to make sure there is someone logged in. That secures it enough.

So, if the fix for the array instead of object:

$result = json_decode($response, true);

works correctly for you, then I think you are all set. Did that fix get you the data you needed? It sounds like you have a working product now.

1 Like

Thank you dear Ernie,
It does not work.
I think I have to explain the problem in more details,
I have a grid like this which is called planning_evaluation. Please look at the image:


The grid is a variable which is called planning_evaluation. Each row has some other variables which are belonged to that variable. If I want to call it, I need to write some code like this:

$lenGrid = count(@=planning_evaluation);
for($x = 1; $x <= $lenGrid;$x++ ) {
@=planning_evaluation[$x][‘material_code’] = $material_code;
@=planning_evaluation[$x][‘remainder’] = $remainder;
}

And the first four columns are gotten from a database based on previous form. But the fifth column must be gotten from the API(from other application). So, the grid information are populated from a query which is written by me, and the fifth column must be gotten from that API.
So, I do not know how to write in calling page?
The latest file is something like this:

pmServer = “http://localhost:1367/rest-api2/api-alis.php?material_code=”;
$lenGrid = count(@=planning_evaluation);
for($x = 1; $x <= $lenGrid;$x++ ) {
@=planning_evaluation[$x][‘material_code’] = $material_code;
@=planning_evaluation[$x][‘remainder’] = $remainder;
}

$url = $pmServer.$material_code;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$result = json_decode($response, true);
foreach ($result as $results) {
echo "{$results->material_code} : {$results->importation_quantity}
";
}
$quantity1 = $results->material_code;
$quantity2 = $results->importation_quantity;

@@remainder = $quantity2;

Thanks in advance for your patience and valuable time.
Very best regards

Well, the calling page seems to be missing a $ at the beginning of pmServer. Assuming that is a typing error. And, what does @= do in your code. I have never seen that used at a beginning of a line.

1 Like

Thanks again,
A grid is a graphic design that presents data in a tabular format consisting of columns and rows.
Each row in the grid is stored as an inner associative array where the grid field names are the ID’s set in the designer for each control inside the grid and the entered data are the values.

For example, the values in the “EmployeesGrid” can be set by querying a table named Employees which also has the fields Name, Salary and HireDate.

$query = ‘SELECT Name, Salary, HireDate FROM Employees’;
$result = executeQuery($query);
if (is_array($result) and count($result) > 0)
@=EmployeesGrid = $result;

This is an example of a grid and its regulation in my application. So, let’s back to my example,

image
In this application, if I want to get material_code and remainder from that variable(grid). So, I need to use something like that to be a standard variation. ($material_name and $remainder).

Hence, what I want is that getting material_code from the grid and also, API must fill $remainder rows(importation_quantity) based on the first column(material_code)
I hope it would be enough to clarify the grid (@=) in the special software.
Kind Regards

Okay, so where is it failing then? If the routine is working well and you are using the array, what is not working. Since we added the ,true to the json code, you said it was creating the array correctly. What else is not working?

1 Like

Dear Ernie, I tried to do that step by step of aforementioned code to figure out which part is failed.

$pmServer = "http://localhost:1367/rest-api2/api-alis.php?material_code="; $lenGrid = count(@=planning_evaluation);

$material_code =array();

for($x = 1; $x <= $lenGrid;$x++ ) {
$material_code[$x] = @=planning_evaluation[$x][‘material_code’];
$url[$x] = $pmServer.$material_code[$x];
$client[$x] = curl_init($url[$x]);
curl_setopt($client[$x],CURLOPT_RETURNTRANSFER,true);
$response[$x] = curl_exec($client[$x]);
@=planning_evaluation[$x][‘toward_order’] = $response[$x]


The above code is Ok, and it is populated in the related column based on its material_code.
But if I add the following code:

pmServer = “http://localhost:1367/rest-api2/api-alis.php?material_code=”;
$lenGrid = count(@=planning_evaluation);
$material_code =array();
for($x = 1; $x <= $lenGrid;$x++ ) {
$material_code[$x] = @=planning_evaluation[$x][‘material_code’];

$url[$x] = $pmServer.$material_code[$x];
$client[$x] = curl_init($url[$x]);
curl_setopt($client[$x],CURLOPT_RETURNTRANSFER,true);
$response[$x] = curl_exec($client[$x]);
$result[$x] = json_decode($response[$x]);
@=planning_evaluation[$x][‘toward_order’] = $result[$x];
foreach ($result[$x] as $results[$x]) {
echo "{$results[$x]->material_code} : {$results[$x]->importation_quantity}
";
}
$quantity2[$x] = $results[$x]->importation_quantity;
}

I see this error: Cannot use temporary expression And also this (object object) is populated in the mentioned coulmnn. What is the problem? I would be appreciated if you help me with this.

Thanks in advance.
Very best regards

Sorry, I was not available much lately. I just reviewed your posted code. I do not think you can index cURL objects as an array entry. An array of objects may interfere with the use of the object. I understand why you might want to index an array of material codes sent by Json, but there is no reason to create an array of all the cURL objects. Why waste the processing time to index them all. Just loop thru the material codes, process the cURL for each and store the results into your indexed results array. Just do not using indexing of the cURL objects. ( Meaning $client. as each curl call is a process of it’s own. )

Not sure if that makes sense or not, but, try removing all the indexing from the curl sections…
( By the way, what line gave you the “cannot use temporary expression” error??? )

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service