开发者

Update a MySQL db via link in PHP

What I am trying to do is call a php class to update a connected mysql db, without changing the page. I am thinking I can do it with Ajax, but I am not certain. I have seen tons of examples using forms, but I am looking for a simple <a href="#">link</a>开发者_Python百科;.


To expand on Khez's comment, using jquery you could use something like:

<html>
<head>
<script type="text/javascript" src="PathToJquery"></script>
<script type="text/javascript">
$(document).ready (function ()
{
    $('#elID').click(function ()
    {
        $.get('urlToChangeDB?variable=value');
    }
}
</script>
</head>
<body>
<a href="#" id="elID">Link</a>
</body>
</html>

You will need to inlude the jquery libray


Easiest way is to use some Ajax, probably through JQuery. A simple example would be to take a form like

Form.php

<form id="ratingform" name="ratingform">        
    <input type="text" id="id" name="id" />

    <input type="text" id="rating" name="rating" />

    <input type="submit" id="loginsubmit" name="loginsubmit" value="Submit!" />
</form>

Then link it with some JQuery to intercept the form, and send it to a PHP file

JQuery.js

$(document).ready(function(){
    $("#ratingform").submit(function(event) {
        $.ajax({
            type: "POST",
            url: "rate.php",
            data: $('#ratingform').serialize(),
                datatype: "json",
            success: function(data){
                var ret = jQuery.parseJSON(data);
                    if(ret.result == "true")
                        // Success
                    else
                        // Failure
            }
    });
    event.preventDefault();
    });
});

Then, create the PHP file to interpret it

rate.php

$stmt = $sql->dbh->prepare("INSERT INTO `rating` (`ID`, `Rating`) VALUES (:id, :rating)");

$stmt->bindValue(':id', $_POST['id']);
$stmt->bindValue(':rating', $_POST['rating']);

$result = $stmt->execute();

echo json_encode(array('result' => "{$result}"));

die();

Essentially, the JQuery intercepts the form action and cancels it, then uses serialize() to package up the data and set it to rate.php as POST data. Then rate.php handles it as a normal POST submission, and echo()s a JSON encoded result of either "true" or "false", depending on whether or no the SQL query was successful, which is sent back to the JQuery script. The JQuery interprets the JSON object, then performs actions based on whether or not the SQL Query was successful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜