checked="checked" /> Male checked="checked" /> Female 这里是一个更新值的例子 -6ren">
gpt4 book ai didi

PHP - 如何在单击单选按钮时将数据更新到 MySQL

转载 作者:行者123 更新时间:2023-11-29 01:09:30 25 4
gpt4 key购买 nike

保存性别的例子

<form action="save.php?id=<?=$id?>" method="post">
<p><label><input name="gender" type="radio" value="male" <?php if($gender=='male'){?>checked="checked"<? }?> /> Male</label></p>
<p><label><input name="gender" type="radio" value="female" <?php if($gender=='female'){?>checked="checked"<? }?> /> Female</label></p>
</form>

这里是一个更新值的例子

  if ($_REQUEST['gender']) {
mysql_query("UPDATE users SET gender='$gender' WHERE id='" . $id . "'") or die(mysql_error());
}

如何在我们点击性别时将值自动保存到数据库中。让我知道。

最佳答案

让你走上更漂亮的道路的东西:

  // $_POST is way cooler than $_REQUEST
if (isset($_POST['gender']) && !empty($_POST['gender'])) {

// sql injection sucks
$gender = my_real_escape_string($_POST['gender']);

// cast it as an integer, sql inject impossible
$id = intval($_GET['id']);

if($id) {
// spit out the boolean INSERT result for use by client side JS
if(mysql_query("UPDATE users SET gender=$gender WHERE id=$id")) {
echo '1';
exit;
} else {
echo '0';
exit;
}
}
}

假设相同的标记,一个 Ajaxy 解决方案(使用 jQuery ):

<script>
var id = <?=$id?>;

// when the DOM is ready
$(document).ready(function() {

// 'click' because IE likes to choke on 'change'
$('input[name=gender]').click(function(e) {

// prevent normal, boring, tedious form submission
e.preventDefault();

// send it to the server out-of-band with XHR
$.post('save.php?id=' + id, function() {
data: $(this).val(),
success: function(resp) {
if(resp == '1') {
alert('Saved successfully');
} else {
alert('Oops, something went wrong!');
}
}
});
});
});
</script>

关于PHP - 如何在单击单选按钮时将数据更新到 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1626730/

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