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

时间:2016-04-18 10:14:43

标签: javascript php mysql ajax mysqli

嗨我想在用户点击下面的按钮时更新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);
}
?>

1 个答案:

答案 0 :(得分:2)

在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(isset($_GET['id']) && !empty($_GET['id']))
{
    $id = $_GET['id'];
    include('database_connection.php');

    $update = "UPDATE id SET id = id + 1 WHERE id = '".$id."'";

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