Load button + MYSQL database data by replacing "Select * From table limit 18"

0

I want to configure a button so that whenever I press the LOAD button + the limit 18 always add +18.

EXAMPLE: $ sql="SELECT * FROM portfolio ORDER BY id DESC limit 18";

CLICKED BUTTON

$ sql="SELECT * FROM portfolio ORDER BY id DESC limit 36";

CLICKED BUTTON

$ sql="SELECT * FROM portfolio ORDER BY id DESC limit 54";

I've put this limit to rearrange the layout and appear only 18 blocks on my site and always carry +18 at the push of a button.

CODE:

<div class="grid">

      <?php
$servidor = 'localhost';
$banco      = 'apixel_galeria';
$usuario  = 'root';
$senha    = '';
$link     = @mysql_connect($servidor, $usuario, $senha);
$db          = mysql_select_db($banco,$link);
if(!$link)
{
    echo "erro ao conectar ao banco de dados!";exit();
}

$sql = "SELECT * FROM portfolio ORDER BY id DESC limit 18";
$query = mysql_query($sql);

while($sql = mysql_fetch_array($query)){
$id = $sql["id"];
$nome = $sql["nome"];
$tipo = $sql["tipo"];
$desc = $sql["desc"];
$menu = $sql["menu"];
$imageM = $sql["imageM"];
$imageF = $sql["imageF"];
    ?>
          <div class="element-item <?php echo "$menu";?>" data-category="transition">
       <a href="#portfolioModal54" class="portfolio-link" data-toggle="modal">
                                <img src="<?php echo "$imageM"?>" alt="project 2">
             <div class="mask">    <div class="conteudo_mask" style="
    transform: translateY(-50%);
    top: 50%;
    position: relative;
    /* float: left; */
    ">                   <h1><?php echo "$nome"?></h1>                   <div id="lin" style="
    width: 200px;
"></div>                   <h2><?php echo "$tipo"?></h2>                                                    </div><h3 style="
    transform: translateY(-50%);
    top: 50%;
    position: relative;
">VEJA <br><img src="images/mais.png" alt="mais" style="width: 20px;height: 19px;margin-bottom: -1px;margin-top: 3px;"></h3></div>
                                </a>
  </div>

        <?php
}
?>
</div>
        <!-- BOTÃO CARREGAR MAIS-->
       <div id="rend-more">
            <button class="button bt1" style="width: 262px; height: 50px; border: 1px solid rgb(84, 128, 128); position: relative; top: 30%; left: 50%; transform: translateX(-50%); cursor: pointer;  background-color: white;">
                <h2 style="text-align: center;color:#4d8984;font-family: 'Gotham-Thin';float: left;font-size: 25px;padding-left: 30px;padding-top: 5px;">CARREGAR</h2>
                <h3 style="padding-left: 5px;float: left;font-size: 25px;color:#4d8984;font-family: 'gotham-bold';padding-top: 5px;">+</h3></button>
        </div> 
    
asked by anonymous 30.11.2015 / 20:54

1 answer

1

Good afternoon, my friend,

EDIT -

For your comments above, you want the data to be loaded dynamically, right? So you'll need to sober up on a bit of ajax.

Edit -

Below is a small example, remembering that I did not validate everything and did not format html, it's a simple example.

In the page, you will do the select in the database, bringing the results of the data, with a limit defined by you.

page: Pórtifolio.php

    <?php

function fn_conexao(){

    $dbuser = "admin";
    $dbpass = "1234";

    try {

        $pdo = new PDO('mysql:host=localhost;dbname=seu_banco',  $dbuser, $dbpass);
        $pdo -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
        $pdo->exec("SET CHARACTER SET utf8");//corrige os acentos na hora de gravar no BD
    } catch(Exception $e) {

        echo 'Erro na conexao: ' . $e->getMessage();
    }

    return $pdo;
}

function dados($pdo){

    try {   

            if(!isset($_GET['id']) or $_GET['id'] == null){

                $id = 0; //se o GET nao for enviado o for enviado como nullo , a variável ID pega o valor de 0

            }else {

                $id = $_GET['id']; //pega o valor passado via GET
            }

            $arr = array();

          //aqui , coloquei o limit como 2 para ficar mais facil os testes
            $sql = "SELECT * from portifolio where id > $id limit 2";
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            $linha = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if($stmt->rowCount() >= 1){

                return $linha; //retorna o resultado da query

            }else {

                return 0;

            }
        } catch(Exception $e) {

            print 'Erro ao inserir os dados no banco: ' . $e->getMessage();
            $conexao = desconecta($conexao);

        }
}

$conexao = fn_conexao();
$dados = dados($conexao);

$dados = json_encode($dados); //converte o resultado para json

print $dados; //imprime os dados na tela
?>

On your page that will display the protifolio, you will make a request to get the data returned in json.

portifolio.php

    <script>

var corpo = ""; //define a variavel corpo como global

function pegaDados()
{
    var id = document.getElementById("ultimo_id").value; //pega o valor do campo "ultimo_id"

    jQuery.ajax
        ({

            url: "json.php?id="+id,
            dataType: "json", //Tipo de Retorno
            success:
            function(data) {

                var pt1 = "";
                var i = 1;
                var ultimo_id = 0;

                  var size = 0, key;
                  for (key in data) {
                        if (data.hasOwnProperty(key)) size++; //cod para contar o tamanho do array multidimensional

                    }//size , variavel com o tamamho do array

                 for(i = 0; i < size; i++){ //monta o html para exibir os dados

                     pt1 += '<div id="nome">Nome: '+data[i].nome+'</div> <div id="foto">Foto: '+data[i].img+'</div>';
                     ultimo_id = data[i].id;
                  }

                  monta_html(pt1);
                 document.getElementById("ultimo_id").value = ultimo_id; //atribui o valor do ultimo id para o campo "ultimo_id"                    

            }
        });

}


function monta_html(dados){

  corpo += dados; //pega os dados da funcao pegaDados , a junta aos dados que ja tem armazenado, assim ,sempre que clicar no botao 
                  //CARREGA +  , ele manterá os dados que foram pesquisados antes.
                  //Assim ,é feita uma consulta pequena ,nao sendo necessarios pesquisar os dados ja bsucados + novos valores.

  document.getElementById("demo").innerHTML = corpo; //joga o valor para um elemento html

}

</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="hidden" value="0" id="ultimo_id"><!-- campo oculto que armazena o valor do ultimo ID buscado no banco -->

<button type="button" onClick="pegaDados();">CARREGA +</button>

<br>

Dados: <span id="demo"></span>

As you can see, I pass the value of the last searched id, so on your page that will mount the return json (getPortifolio.php), you do a _get ['id'] and use it in where (select * from portifolio where id > $ id limit 18). Thus, it picks up the data in the following way, being limited to 18 results.

Now, you have to organize the json result to be able to display on your screen. I recommend tbm, check how many records you have in your "portifolio" table, so when you do not have more records to look for, the LOAD + button is disabled.

With the javascript I can not help much because I do not have much knowledge about it, but I tested it on my machine and it ran normal.

    
30.11.2015 / 22:15