Adrian Arceo
Adrian Arceo

Reputation: 11

When click on link execute onclick="function()" to increment a value on my database

Im making a forum and in one of the pages i show the topics i have with an id i got from the page before, and in that page i also want to show how many visits the topics have, as such i call the id of the topic, put it in a function that i call to when i click on a link with onclick, so that once somebody clicks on it to access it, it also updates the visits count on the database. Point is, it doesnt work.

PHP CALL

<?php
    include("db.php");
    $sql="SELECT `id`, `nombre`, `creador`, `dept_no`, `fechac`, `visitas` FROM `temas` WHERE `dept_no`=".(desencryptar($_GET["id"]));
    if($resultado = $mysqli->query($sql)) {
       if($resultado->num_rows>0){
          while($fila = $resultado->fetch_assoc()) {
             $id=$fila["id"];
             $nombre=$fila["nombre"];
             $creador=$fila["creador"];
             $dept_no=$fila["dept_no"];
             $fechac=$fila["fechac"];
             $visitas=$fila["visitas"];  ?>

After which i call it when showing it.

HTML

<tr>
   <td>
      <a onclick="visitas(<?php echo $id;?>)" id="tema" href="posts.php?id=<?php echo encryptar($id);?>" target="_self"><?php echo $nombre;?></a>
      <div style="padding-top:5px">
           <span>Por<a href="perfil.php?id=<?php echo $creador;?>"> <?php echo $creador;?></a>, <?php echo $fechac;?></span>
       </div>
   </td>
   <td style="text-align: center;"><?php echo Contar($id);?></td>
   <td style="text-align: center;"><?php echo $visitas;?></td>
   <td>Por<a href="perfil.php"> <?php echo $creador;?></a><br><span>En </span><?php echo $fechac;?></td>

PHP FUNCTION i created on a functions.php

function visitas($valor) {
include("db.php");
$sql2="UPDATE `temas` SET `visitas` = `visitas` + 1 WHERE `id`=".$valor; }

Upvotes: 0

Views: 149

Answers (1)

MehdiDev
MehdiDev

Reputation: 21

you are using a Javascript Function visitas() and created a PHP function visitas ?

Know that Javascript function can't execute PHP function...

You need to create a Javascript function that will execute a Ajax request to a php file that contain your Php function, then redirect the user after success response.

Example:

jQuery Ajax POST example with PHP

Upvotes: 1

Related Questions