Update photo counter instantly

1

I'm making a website, where I display products that are registered in a database. In the table, there is a field that I call relevance and I wanted that when someone clicked on the image I would increment that field. I have no idea how to do this and wanted some tips. I tried by inclick of the image a php function that gave update in that field, but I know it does not work to do so by the way onclick works.

Although I knew it would not work, follow the code below to understand what I wanted to happen:

while($dados=mysql_fetch_array($sql)){
                    $aux=$dados['relevancia']+1;
                    $res= "UPDATE cwfolheados.produtos SET relevancia=".$aux." WHERE codigo=".$dados['codigo']."";
                echo "<li><a href='".$dados['foto']."' onclick='mysql_query($res)' style=' margin-left:0' data-lightbox='image-1' data-title=".$aux2.">
            <img  style=' width:200px; height:150px;  ' border='0' alt='image 02' src='".$dados['foto']."' />
            <figcaption>".$dados['nome']." - ".$dados['codigo']."</figcaption></a></li>     ";}
    
asked by anonymous 05.03.2015 / 03:25

2 answers

2

You can build a code structure using the jQuery method on and ajax :

HTML:

<img id="img-id" class="img-class" src="img/imagem.jpg" alt="Minha imagem" />

Javascript:

$('.img-class').on('click', 'img', function (e) {
    var id = this.id;

    $.ajax({
        url: 'ajax.php',
        type: 'post',
        data: id
    }).done(function(data) {
        if ( data == 'relevancia incrementada' ) {
            alert('Sucesso.');
        } else {
            alert(data);
        }
    });
});

PHP:

<?php
    if ( !isset( $_POST["id"] || empty($_POST["id"]) ) ) {
        echo "id nao setado ou nulo";
        exit();
    }

    $id = $_POST["id"];

    try {
        $conn = new PDO("mysql:host=localhost;dbname=database", "root", "");
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $this->conn->prepare("UPDATE tabela SET relevancia = relevancia + 1 WHERE codigo = :id");
        $stmt->bindParam( ":id", $id );

        $stmt->execute();
        $result = $stmt->rowCount();

        if ( $result > 0 ) {
            return "relevancia incrementada";
        }
    } catch(PDOException $e) {
        return "erro: " . $e->getMessage();
    }
  • Note that the id of each image will be pre-retrieved from the database.
  • I've used PDO in the example, but it also works with mysql_ functions although it's highly recommended to abandon those functions.
05.03.2015 / 04:09
1

As I explained in the other response , the onclick attribute can not be used in this way.

All you need to do is run the update every time the script that shows the product loads. This way, with each view the counter will be incremented by 1.

Ex:

mysql_query("UPDATE cwfolheados.produtos SET relevancia=relevancia+1 WHERE codigo=".$dados['codigo'].");

I used as your query and modified only the sum of the column value (which can be done directly in SQL). I also assumed that the product code is in $dados['codigo'] as you reported.

Another thing, there is no need to use while when you know that your query will return only one result (a single product in this case). You can only use $dados = mysql_fetch_array($sql); that the effect will be the same.

    
05.03.2015 / 03:57