单击链接将数据更新到mysql数据库

我有办法在点击链接时将数据更新到mysql数据库吗? 我想在我的网站上创建一个评论投票系统,这样当用户点击“投票给这个评论”链接时,+1应该被发送到数据库…

怎么可能?

HTML

PHPvote.php

 Missing item parameter' ); } $item = (int) $_POST['item']; if( @mysql_query( "UPDATE `items` SET `vote`=`vote`+1 WHERE `id`=$item" ) ) { if( isset( $_POST['format'] ) && $_POST['format']=='json' ) die( json_encode( array( 'result'=>true ) ) ); die( 'Score for item #'.$item.' incremented' ); } header( 'HTTP/1.1 500 Internal Server Error' ); if( isset( $_POST['format'] ) && $_POST['format']=='json' ) die( json_encode( array( 'result'=>false ) ) ); die( 'Score for item #'.$item.' FAILED to incremented' ); 

jQuery的

 $( document ).ready( function() { $( 'form[action="/vote.php"]' ).each( function() { $( this ).replaceWith( 'Vote Up' ); } ); $( 'span[class="vote"]' ).click( function() { var $this = $( this ); $.ajax( { type : 'POST' , url : '/vote.php' , data : $( this ).attr( 'parameter' )+'&format=json' , dataType : 'json' , success : function( data , status , XHR ) { if( data.result===true ) alert( 'Voted Up' ); else alert( 'Something Unexpected Borked' ); } , error : function( XHR , status , error ) { alert( 'Something Borked' ); } } ); } ); } ); 

注意:这是一个未经测试的解决方案,但我会考虑开始调试和测试的起点。

更新:根据@Artefacto的建议将行为更改为POST。

当然,创建一个PHP脚本来更新数据库,就像提交了常规表单一样,然后在单击链接时使用Javascript向该脚本发出请求。

请参阅AJAX简介 。

使用AJAX (使用其中一个可用的框架jQuery,mootools,Dojo,…):每当用户点击链接时,附加的动作就会被触发并执行“魔术”。

大多数情况下,这将向服务器发送带有注释ID和/或任何其他所需数据的AJAX请求,脚本将更新数据库。

您已经使用jQuery标记了问题, http: //api.jquery.com/category/ajax/是一个很好的起点。

在HTML中:

 vote 

在PHP中:

 $Q = 'UPDATE `votes` SET `count` = `count` + 1 WHERE `answer_id` = ?'; $db_connection->prepare($Q); $db_connection->bind_param('i', $_GET['answer_id']); $db_connection->execute(); 

准备就绪后,使用AJAX无需重新加载页面即可完成此操作。 将函数绑定到投票链接并以相同的方式将请求发送到网页,但是异步。

在jQuery中使用类似的东西:

 $.get('update.php?id=1', function(data) { alert('Thanks for voting'); });