1. 程式人生 > >PHP點贊功能

PHP點贊功能

Html部分程式碼:

<?php

$id = $_GET['id'];

require_once 'mysqlHelper.php';

$db = new mysqlHelper('localhost','root','root','dianzan');

$sql = "select * from news where id = '$id'";

$news = $db->GetOneData($sql);

?>

<!doctype html>

<html>

<head>

<script

 src="jquery-1.9.1.min.js"></script>

<meta charset="UTF-8">

</head>

<body>

<h1><?php echo $news['title'];?></h1>

<pre>

<?php echo $news['content'];?>

</pre>

<input type="hidden" name="id" value="<?php echo $id;?>">

點贊數:<span id="s"><?php echo $news['dianzan'];?></span>

<button id="btn">點贊</button>

</body>

</html>

 

Js程式碼:

 

$("#btn").click(function(){

    $.ajax({

        

url:"index.php",

        type:"POST",

        data:{id:<?php echo $id;?>},

        async:false,

        success:function(data){

            if(data === false){

                alert('點贊失敗!');location.href='dianzan.php?id=<?php echo $id;?>';

            }else{

                alert('點贊成功!');$("#s").html(data);

            }

        }

    })

})

 

 

PHP程式碼:

<?php

header("Content-type:text/html;charset=utf-8");

require_once 'mysqlHelper.php';

$db new mysqlHelper('localhost','root','root','dianzan');

$id $_POST['id'];

$sql "UPDATE news SET dianzan = dianzan +1 WHERE id = '$id'";

$res $db->execSql($sql);

if($res){

    $dz $db->getOneData("select * from news where id = '$id'");

    $dz $dz['dianzan'];

    echo $dz; 

}else{

    return false; 

}

?>