Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Aktualisieren Sie die Daten in der MySQL-Datenbank, indem Sie auf einen Link klicken

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

Hinweis: Dies ist eine ungetestete Lösung, aber ich würde sie als Ausgangspunkt für das Debuggen und Testen betrachten.

AKTUALISIERT: Geändertes Verhalten zu POST basierend auf Ratschlägen von @Artefacto.