Paginating content without the need for a database

Seeking assistance on implementing pagination for displaying trading history API responses, without utilizing a database. Can anyone provide guidance and help with the necessary logic?

Here is an excerpt of my code:

     <?php

 error_reporting(E_ALL);

$url = "https://www.myfxbook.com/api/login.json?";

$email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d1cfdad6c5dcd2c3d4d6c4c3f7d0dad6dedb99d4d8da">[email protected]</a>";
$password="**********";


$url .= '&email='.$email;
$url .= '&password='.$password;

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$result = curl_exec($ch);
$propertyarr = json_decode($result, true);
$session = $propertyarr['session'];
$url2 = "https://www.myfxbook.com/api/get-history.json?";
$url2 .= 'session='.$session;
$url2 .= '&id=908596';

$ch2 = curl_init(); 
curl_setopt($ch2, CURLOPT_URL,$url2); 
curl_setopt($ch2, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);

$result2 = curl_exec($ch2);
$result2 = json_decode($result2);
$result2 = (array)$result2;


$newres = array();
foreach ($result2 as $res) {
            $newres  = $res;

    }
    var_dump($newres['0']);
    ?>
    <div class="trade_history">
    <div id="trade_titles" align="center" >
        <h>OPEN TIME</h>
        <h>CLOSE TIME</h>
        <h>OPEN PRICE</h>
        <h >CLOSE PRICE</h>
        <h>LOTS</h>
        <h>TYPE</h>
        <h>PAIR</h>
        <h>PIPS</h>
        </div>
    <?php
    //
    //echo '<table border="1">';

    for($i=0;$i<=sizeof($newres)-1;$i++)
    {

        ?>
        <div id="trade_data">
        <div id="opent_time">
                <?php echo $newres[$i]->openTime; ?>
                </div>
                <div id="close_time">
                <?php echo $newres[$i]->closeTime; ?>
                </div>
                <div id="opent_price">
                <?php echo $newres[$i]->openPrice; ?>
                </div>
                <div id="close_price">
                <?php echo $newres[$i]->closePrice; ?>
                </div>
                <div id="lots">
                <?php echo $newres[$i]->sizing->value; ?>
                </div>
                <div id="type">
                <?php echo $newres[$i]->action; ?>
                </div>
                <div id="pair">
                <?php echo $newres[$i]->symbol; ?>
                </div>
                <div id="pips">
                <?php echo $newres[$i]->pips; ?>
                </div>

                </div>
<?php


    }?>
    </div>

Currently, the response is displayed as follows:

Is it possible to format the results in the following manner?

If you can offer any assistance, I would greatly appreciate it. Thank you in advance.

Answer №1

Thanks to everyone for their prompt responses.

I finally grasped the logic. Here is the code with the solution provided:

<?php

//error_reporting(E_ALL);

$url = "https://www.myfxbook.com/api/login.json?";

$email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e086988d81928b859483819394a0878d81898cce838f8d">[email protected]</a>";
$password="********";


$url .= '&email='.$email;
$url .= '&password='.$password;

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$result = curl_exec($ch);
$propertyarr = json_decode($result, true);
$session = $propertyarr['session'];
$url2 = "https://www.myfxbook.com/api/get-history.json?";
$url2 .= 'session='.$session;
$url2 .= '&id=908596';

$ch2 = curl_init(); 
curl_setopt($ch2, CURLOPT_URL,$url2); 
curl_setopt($ch2, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);

$result2 = curl_exec($ch2);
$result2 = json_decode($result2);
$result2 = (array)$result2;


$newres = array();
foreach ($result2 as $res) {
            $newres  = $res;

    }
    //var_dump($newres['0']);
    ?>
    
    <div class="trade_history">
    <div id="trade_titles" align="center" >
        <h>OPEN TIME</h>
        <h>CLOSE TIME</h>
        <h>OPEN PRICE</h>
        <h >CLOSE PRICE</h>
        <h>LOTS</h>
        <h>TYPE</h>
        <h>PAIR</h>
        <h>PIPS</h>
        </div>
    
    <?php
    if(empty($_GET['page_num']))
    {
        $page_num=1;
    }
    else
    {
    $page_num = $_GET['page_num'];
    }

    $i=$page_num*10;
    $srow = $i;
    $endrow = $srow-10;
   
    
    for($i=$endrow;$i<=$srow-1;$i++)
    {

        ?>
        
        <div id="trade_data">
        <div id="opent_time">
                <?php echo $newres[$i]->openTime; ?>
                </div>
                <div id="close_time">
                <?php echo $newres[$i]->closeTime; ?>
                </div>
                <div id="opent_price">
                <?php echo $newres[$i]->openPrice; ?>
                </div>
                <div id="close_price">
                <?php echo $newres[$i]->closePrice; ?>
                </div>
                <div id="lots">
                <?php echo $newres[$i]->sizing->value; ?>
                </div>
                <div id="type">
                <?php echo $newres[$i]->action; ?>
                </div>
                <div id="pair">
                <?php echo $newres[$i]->symbol; ?>
                </div>
                <div id="pips">
                <?php echo $newres[$i]->pips; ?>
                </div>

                </div>

<?php


    }?>
    </div>

    <div class="pagination">
            <?php $numpages = count($newres)/10;
            $numpages = ceil($numpages);


            $Path='forex-signals';
            $URI='http://localhost/fx/'.$Path;
            $current = $page_num;
            $prev = $current-1;
            $next = $current+1;


                echo '<div id="first"><a href='.$URI.'?page_num=1#trade_history>First</a></div>';   
                echo '<div id="prev"><a href='.$URI.'?page_num='.$next.'#trade_history>Previous</a></div>';
            for($n=1;$n<=$numpages;$n++)
            {
                echo '<div id="page_num"><a href='.$URI.'?page_num='.$n.'#trade_history>'.$n.'</a></div>';
            }
            echo '<div id="next"><a href='.$URI.'?page_num='.$next.'#trade_history>Next</a></div>';
            echo '<div id="last"><a href='.$URI.'?page_num='.$numpages.'#trade_history>Last</a></div>'; 

            ?>

    </div>

Answer №2

If you're looking to easily display a table on your website, I recommend checking out datatables.net. It's a great jQuery plugin that allows you to customize and present your data in a user-friendly way. The default setup should meet your requirements perfectly.

Answer №3

Are you in a situation where you're retrieving a large array from a service API without the use of a database?

If you're looking for a solution on the PHP side, I recommend creating a temporary storage option for the incoming data.

  • temporary file with serialized array data
  • session storage
  • SQLite database

Having this store will prevent unnecessary re-fetching of data from the service API and allow for independent pagination calls to your script.

The pagination logic revolves around using 'array_slice':

$items_total = count($items);
$per_page = 10;    
$max_pages = ceil($items_total / $per_page);    
$page = array_slice($items, $per_page * intval($_GET['page']) - 1, $per_page);

if($_GET['page'] > 1) {
    $prev_link = '<a href="script.php?page='.($_GET['page']-1).'"> previous </a>';
}

if($_GET['page'] < $max_pages) {
    $next_link = '<a href="script.php?page='.($_GET['page']+1).'"> next </a>';
}

An alternative approach is to utilize a JavaScript/client-side solution, where the entire dataset is passed from PHP to JS as JSON and implemented into a table plugin like datatables or tablesorter ().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach to tackle this design?

As a newcomer to React, I'm facing challenges in positioning components. The layout I envision is consistent across all pages, with certain elements remaining the same. Should I utilize a grid system for this design? How should I approach achieving th ...

Refresh cookies on monitor using Vue.js

I am in the process of implementing cookies on my website. Initially, I have set up the cookies to be initialized with an empty object when the component is mounted. The goal is to update the cookie whenever the object data changes, but unfortunately, it&a ...

An issue arises when trying to import the modal popup

Hey there! I'm currently trying to implement a modal popup in react-bootstrap, but I keep running into an error that says "Props not defined". I followed the instructions from the react-bootstrap documentation, but I can't seem to figure out what ...

Inheriting the Powers of Magical Sensation

I am trying to implement the concept of inheritance in PHP classes based on an article I found on this website. The article suggests using a base class to define a getter function and then have other classes inherit from it. This would save me from rewriti ...

When you open the responsive navigation bar, it automatically closes

After creating a website some time ago, I decided to make it responsive by adding a menu. However, I encountered an issue where the menu bar opens but immediately closes after showing the entire list. Here is the HTML code for the menu: <!-- start men ...

StartsWith() function failing when used in conjunction with takeWhile()

I'm trying to iterate over an Immutable List and create a new list containing only the entries that start with a specific string. In this case, I want to find all states that begin with the letter 'D'. However, instead of returning a list wi ...

Number of database rows - PHP prepared statements - querying data

I'm having trouble figuring out how to retrieve the number of rows from the database using my query. Every time I run the query, it just returns zero even though the data is in my database. $username = $_POST['username']; $hashedPassword = ...

Import and load numerous JSON files into a responsive and visually appealing Bootstrap table

I am new to coding in javascript and I'm seeking assistance in loading multiple JSON files to populate a bootstrap table. Currently, I've managed to create a table by manually combining the content from different files into one variable called l ...

React-router-sitemap lacks a definition for 'Require'

According to the official documentation here, this is how the sitemap-builder.js file should be structured: require('babel-register'); const router = require('./router').default; const Sitemap = require('../').default; ( ...

Learn how to store the outcomes of an HTTP operation within array.map() in JavaScript

Having read numerous articles, I am a complete beginner when it comes to async programming and struggling to grasp its concepts. My goal is to map a filtered array of objects and return the result of a function (an amount) to set as the value of pmtdue. De ...

Utilize typehead.js in Python Django to retrieve an updated data list directly from the database

file.js var source = new Bloodhound({ hint: false, datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"), queryTokenizer: Bloodhound.tokenizers.whitespace, // /a_c/p_s/?term=d&category=all remote: "/a ...

Learn how to incorporate a click event with the <nuxt-img> component in Vue

I am encountering an issue in my vue-app where I need to make a <nuxt-img /> clickable. I attempted to achieve this by using the following code: <nuxt-img :src="image.src" @click="isClickable ? doSomeStuff : null" /> Howeve ...

Encoding the output as JSON and displaying the result

This is the PHP code I am using: $query=mysql_query("SELECT * FROM product"); $bla = array(); $numOfRows= mysql_num_rows($query); if ($numOfRows >0) { while ($rows=mysql_fetch_array($query,MYSQL_ASSOC)) { //$pro ...

Is AngularJS primarily a client-side or server-side framework, or does it have elements

Is it possible to connect to the database on the server side? I have experience using it on the client side, but can the same method be used on the server side? If it's not suitable for server-side use, should I go with PHP or Node.js for designing ...

TS type defined by JS constants

I am currently working on a project that involves both JavaScript and TypeScript. I am trying to find a solution to reduce code duplication when using JavaScript string constants by converting them into TypeScript types. For example, let's say I have ...

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

searchByTextContentUnderListItemAnchorTag

I would like to utilize the getByRole function for writing my test. However, I am encountering issues when using linkitem or 'link' as the role. It seems that I cannot find the desired element. // encountered error TestingLibraryElementError: The ...

The drop-down menu does not maintain its selected option after the window is refreshed

I am struggling with a dropdown list as shown below: <select class="span2" id ="sort" name= "order_by"> <option >Default</option> <option >Price</option> <option >Color</option> ...

Steps for interacting with a button of the <input> tag in Selenium using Python

As I attempt to complete a form submission, I encounter an issue where clicking the submit button does not produce any action. It seems that the problem lies with the button being tagged as <input>: <input type="submit" name="submit ...

Retrieving the initial array element within a foreach loop

I am just starting with ajax concepts... When I post data using ajax, only the first array from the foreach loop gets posted. Here is the code snippet: <tbody id="presentor"> <?php if(!empty($data)):?> <?php $counter = '0'; for ...