从JavaScript onClick通过Ajax PHP更新数据库

py49o6xq  于 2023-11-15  发布在  Java
关注(0)|答案(1)|浏览(112)

嗨,我想更新id行时,一个用户点击下面的按钮,请帮助,对不起我的英语不好
index.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>

<body>

<a href="javascript:void(0)" onClick="updateId('1')">Id 1</a>
<a href="javascript:void(0)" onClick="updateId('2')">Id 2</a>
<a href="javascript:void(0)" onClick="updateId('3')">Id 3</a>

</body>
</html>

字符串
update.php

<?php 
include('database_connection.php');

$update = "UPDATE id SET id = id + 1 WHERE id = updateId";

if (mysqli_query($connect, $update)) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . mysqli_error($connect);
}
?>

hec6srdp

hec6srdp1#

在index.php文件中

<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>

<a href="javascript:void(0)" onClick="updateId('1')">Id 1</a>
<a href="javascript:void(0)" onClick="updateId('2')">Id 2</a>
<a href="javascript:void(0)" onClick="updateId('3')">Id 3</a>

</body>
</html>

<script>
function updateId(id)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
        {
            alert(xmlhttp.responseText);
        }
    };
    xmlhttp.open("GET", "update.php?id=" +id, true);
    xmlhttp.send();
}
</script>

字符串
在您的update.php中,

<?php 
if(!empty($_GET['id']))
{
    $id = $_GET['id'];
    include('database_connection.php');
    
    $update = "UPDATE id SET id = id + 1 WHERE id = ?";
    
    $connect->execute_query($update, [$id]);
}

相关问题