Heriberto Nol Heriberto Nol - 3 months ago 37
MySQL Question

How to create a load more button using php, pdo and oop

Im trying to create a button like the one in the youtube commentaries but i cant do it, I tried creating a static variable, so every time i press a button to load more the variable will be increased but it just can be increased once, maybe a for loop can help but i dont have any idea of how to implement it.
(Im loading the ids i have saved in a mysql database but i will change the id for the commentaries i have in other database.) Screen shots:

Here´s the fist time the page is opened
It works the first time i press the button but then it is not increased

<title>Pruebas</title>
<center>
<?php
require 'conexion.php';

class Ver_prublicaciones extends Conexion{
public function Ver_prublicaciones(){
parent::__construct();
}
public function Ver($num){
$sql="SELECT * FROM USUARIOS";
$resultNum=$this->con->query($sql)->rowCount();

$sql2="SELECT * FROM USUARIOS LIMIT 0,$num";
$resultCon=$this->con->query($sql2);
$array=$resultCon->fetchAll(PDO::FETCH_ASSOC);
foreach ($array as $value){
echo $value['ID'] . "<br>";
}
}

}

$numero;
$numero=2;

if(isset($_POST['cargar'])){
$numero++;
}


$prueba=new Ver_prublicaciones();
$prueba->Ver($numero);

?>

<form method="post">
<input type="submit" name="cargar" value="Cargar más resultados">
</form>
</center>

Answer

You need to pass the current value of $numero to be able to increase it on every click.

PHP

// if we got a numero value posted, use that, otherwise set it to 2 as default
$numero = isset($_POST['numero']) ? $_POST['numero'] : 2;

if(isset($_POST['cargar'])){
    $numero++;
}

HTML

<form method="post">
    <input type="hidden" name="numero" value="<?= $numero ?>" />
    <input type="submit" name="cargar" value="Cargar más resultados">
</form>

Here we added the current value of $numero as a hidden field that gets passed on every click.