gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:00:42 24 4
gpt4 key购买 nike

有没有办法在单击链接时将数据更新到 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 - 通过单击链接将数据更新到 mysql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3222697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com