php mysql怎么實現點贊功能
1、index.php 讀取數據庫點贊表的數量。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>點贊</title> <script src="jquery-2.1.1.min.js"></script> <script src="index.js"></script> </head> <body> <button id="btn">贊</button> <span id="result"> <?php $con = mysqli_connect('localhost', 'username', 'password'); if(! $con ) { die('連接失敗: ' . mysqli_error($con)); } mysqli_select_db($con,'jwhuang'); mysqli_query($con,"set names utf8"); $result = mysqli_query($con,"SELECT * FROM zan"); while($row = mysqli_fetch_array($result)) { echo $row['zan']; } mysqli_close($con) ?> </span> </body> </html>
2、server.php 用戶點擊贊按鈕就向數據庫插入一條數據。
<?php header("Content-type:text/html;charset=utf-8"); $con = mysqli_connect('localhost', 'username', 'password'); if(!$con ) { die('連接失敗: ' . mysqli_error($con)); } mysqli_select_db($con,'jwhuang'); mysqli_query($con,"set names utf8"); mysqli_query($con,"UPDATE zan SET zan = zan+1"); $result = mysqli_query($con,"SELECT * FROM zan"); if(isset($_GET['name'])){ while($row = mysqli_fetch_array($result)) { echo $row['zan']; } }else{ echo "贊失敗!"; } mysqli_close($con); ?>
3、index.js 請求數據
$(document).ready(function(){ $("#btn").on("click",function(){ $.get("sever.php",{name:$("#btn").val()},function(data){ $("#result").text(data); }); }); });