在php和mysql上单击counter

liwlm1x9  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(253)

如果有人点击clickmediv,数据库中的计数器就会增加。当前当页面刷新时,计数器增加。

<div class="Hello">Click Me</div>    

<?php 
$find_counts = mysqli_query($conn, "SELECT * FROM ad_section");
 while($row = mysqli_fetch_assoc($find_counts)){
  $current_counts = $row['no_of_clicks'];
  $new_count = $current_counts + 1;
  $update_count = mysqli_query($conn, "UPDATE `ad_section` SET `no_of_clicks`= $new_count");
 }
?>
iyr7buue

iyr7buue1#

好吧。。。所以我将以一种简单实用的方式帮助您理解什么是ajax。。因为一旦你了解了ajax。。你将能够解决这个问题和其他许多问题。
ajax不是一种“语言”或“技术”。。这只是浏览器与服务器交互方式的升级。
以前(在ajax之前,早在ajax之前),当浏览器必须从服务器请求数据/页面时,它必须刷新页面或请求一个全新的页面。。并显示在新窗口上。。但它绝对没有办法在“后台”这样做。。然后不受任何干扰地更新当前显示的html页面。
这就是ajax解决的问题。
所以现在。。通过javascript或jquery(同样的事情)。。您可以向服务器(任何web服务器上的任何端点)发送包含数据的请求。。。还有服务器。。然后有可能读取您发送的数据,以任何方式处理它,并以数据的形式返回结果。。
数据是以json(javascript对象表示法)的格式传递的,这只是一种对数据和数组进行编码的方式
所以你发送一个json,服务器会返回一个json或者一个错误页面(404等等)
魔法现在发生了。。。
你的页面。。从服务器收到结果后。。仍然在发送请求的同一个函数执行中。。。将能够打开结果。。并使用javascript/jquery/dom操作。。将结果插入当前html页或执行任何新操作。。例如显示警报、重定向、动画等。。
这就是它的工作原理:
假设您有一个div,单击该div可以在服务器上设置数据更新,然后从服务器获取结果并刷新自身。。

<div id='clickme'>People clicked ... <span id='howmany'>1</span></div>

<script>

//Not accurate code, I'm just writing from what I remember .. jquery 

$('#clickme').click(function() {
 //event captured on click on 'click me'

 var nothing = ''; //there is no data to be sent, really.. because we will be getting the update from the server on how many people have clicked it.. 
 //AJAX NOW... //sending a post request
 $.post(
 'https://mywebsite/index.php/incrementMe',
 {data:nothing},
 function(data) 
 {
   //this is the function that will receive in its data the result back from the web-server function incrementMe
  var result = JSON.parse(data); //parsing the JSON into javascript object/array

  $('#howmany').html(result['updatedInfo']); //updatedInfo is the variable within the result that was sent back from the server.. which I then.. using DOM manipulation, plug it back into the span ID

}
);
//End of AJAX request... you didn't have to refresh the page..

</script>

在服务器上。。你会有这样的想法:(用php-yii风格写)

public function actionincrementMe()
{
  $data = json_decode($_POST['data']); //got the posted variable and decoded using a PHP function .. to get a PHP array/object
  //well in fact, you don't even need this.. because.. there is no info coming to you from the front end .. but if you had, then this is how you'd receive it.. 

 $newnumber = SQL to find out latest number + 1;

 print json_encode($newnumber); //this is the function that will just answer back the front-end with a json formated data point..which is the variable new number..which you would then have received in the javascript function.

}
smtd7mpg

smtd7mpg2#

其中一种方法是这样做(仅包括我所包含的步骤)
-创建一个具有图像id的表,然后单击计数器
-在图像单击或div单击上实现一个函数(如果有更多图像,则可以使用通用的图像单击函数)
-在函数内部使用ajax实现增加计数的功能

相关问题