繁体   English   中英

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

[英]Update data into mysql database by clicking on a link

单击链接时,有没有一种方法可以将数据更新到mysql数据库中? 我想在我的网站上创建一个评论投票系统,以便当用户单击“为此评论投票”链接时,应该将+1发送到数据库中。

那怎么可能?

的HTML

<form method="post" action="/vote.php">
  <input type="hidden" name="item" value="999">
  <input type="submit" name="submit" value="Vote Up">
</form>

PHP - vote.php

<?php
if( !isset( $_POST['item'] ) ) {
  header( 'HTTP/1.0 404 Not Found' );
  die( '<html><body>Missing <i>item</i> parameter</body></html>' );
}
$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( '<html><body>Score for item #'.$item.' incremented</body></html>' );
}
header( 'HTTP/1.1 500 Internal Server Error' );
if( isset( $_POST['format'] ) && $_POST['format']=='json' )
    die( json_encode( array( 'result'=>false ) ) );
die( '<html><body>Score for item #'.$item.' FAILED to incremented</body></html>' );

jQuery的

$( document ).ready( function() {
  $( 'form[action="/vote.php"]' ).each( function() {
    $( this ).replaceWith( '<span class="vote" parameter="item='+$( this ).find( 'input[name="item"]' ).attr( 'value' )+'">Vote Up</span>' );
  } );
  $( '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中:

<a href="update.php?answer_id=1">vote</a>

在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');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM