Press button + MYSQL Database Data overwriting "Select * From table limit 18"

Asked

Viewed 1,621 times

0

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

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

CLICKABLE BUTTON

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

CLICKABLE BUTTON

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

I put this limit to tidy up the layout and appear only 18 blocks on my site and always press +18 on the 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> 
  • What you want is called PAGINATION. See this tutorial and see if it helps you.

  • 3

    It doesn’t make sense, you’ll be picking up all the values already obtained before each click. Keep the limit and change the WHERE to > the last ID caught in the previous click. Of course there will have to change the logic of the page to load dynamically, or make paginated.

  • so buddy, it’s dynamically, when he squeezes he already carries down the others.

  • Bacco did not understand how I will do it rs, could explain me?

  • 'Cause I don’t see a Where in my code.

1 answer

1

Good afternoon friend ,

EDIT --

By your comment above, you want the data to be dynamically loaded, right ? Then Voce will need to rest on a little ajax.

Edit --

Below , follows a small example , remembering that I have not seen everything and I have not formatted the html , is a simple example .

On the take pagePortifolio.php , you will select the database , bringing the results of the data , with a limit defined by you.

page : pegaPortifolio.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 pick up 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>

<input type="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 ,step the value of the last searched id , then , on your page that will mount the return json (pegaPortifolio.php) , Oce makes a _get['id'] and uses it in Where ( select * from portifolio Where id > $id limit 18) . Thus, it takes the data in second , being limited to 18 results.

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

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

  • Henrique I’m using the Isotope jquery plug to create a gallery that pulls from the database, so it will be dynamically, when clickar it will appear +18 blocks pulled from the BD

  • to assign to my code I need to change something?

  • in the case where the url is: "http://main.xfiddle.com/code_27238237.php?id="+id, I do _get['id'] ??????

  • this Function I do inside the pegaPortifolio.php ???

  • Good afternoon, that. On the take pagePortifolio.php you make the $id = $_GET['id'] . Already in the page portifolio.php , you put the javascript function that sends the request to the page pegaPortifolio.php

  • i’m having trouble understanding :/. how I’m going to do it

  • vc could do the pranksPortifolio.php and portifolio.php of how it would look in my code? In my BD - it’s apixel_gallery TABLE: portfolio

  • Good afternoon @kaiquemix , I edited the code , I left it well commented. Test , the adaptations, that I believe will solve your problem.

  • no inspect element ta appearing this: Failed to load Resource: the responded server with a status of 404 (Not Found) GET http://localhost/pixelsbd/json.php? id=0 404 (Not Found)

  • See the file name and its path. This is not found

  • yes it was the portfolio and not portifolio heehe good now ta appearing only this: GET http://localhost/pixelsbd/json.php? id=0 404 (Not Found)

  • you are giving error in this url... what I put in it?

  • How did you name the file that takes the database data ? In the example, I called it 'json.php' and left it in the same directory as the file that calls it. Check the name of the file in your page portifolio.php in this part : "url:seu_file.php"

  • the portfolio is index.php , and this pegarportfolio I put inside an ajax/pegarportfolio.php folder

  • put so, url: "ajax/pegaPortifolio.php? id="+id, now nothing is happening and shows nothing in the console

Show 11 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.