微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从PHP插入到MySQL(jQuery / AJAX)

我看过很多教程,但是他们很困惑,要做我想做的,我只是不知道如何使用这些教程中的现有东西,并使他们按照我想要的方式工作.

我有一个非常简单的表单,包含一个文本框,标签一个提交按钮.当用户输入表单时,点击提交,我想使用PHP和ajax(使用jquery)将表单的结果插入到MysqL数据库中.

有人可以告诉我这是如何实现的?只是一些非常基本的东西就是我以后让我开始.任何帮助是赞赏.

谢谢

嗨,这里只是一个简单的例子:

HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Quick JQuery Ajax Request</title>
        <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <!-- include the jquery lib -->
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            var ajaxSubmit = function(formEl) {
                // fetch where we want to submit the form to
                var url = $(formEl).attr('action');

                // fetch the data for the form
                var data = $(formEl).serializeArray();

                // setup the ajax request
                $.ajax({
                    url: url,data: data,dataType: 'json',success: function() {
                        if(rsp.success) {
                            alert('form has been posted successfully');
                        }
                    }
                });

                // return false so the form does not actually
                // submit to the page
                return false;
            }
        </script>

    </head>
    <body>

        <form method="post" action="process.PHP"
              onSubmit="return ajaxSubmit(this);">
            Value: <input type="text" name="my_value" />
            <input type="submit" name="form_submit" value="Go" />
        </form>

    </body>
</html>

process.PHP脚本:

<?PHP

function post($key) {
    if (isset($_POST[$key]))
        return $_POST[$key];
    return false;
}

// setup the database connect
$cxn = MysqL_connect('localhost','username_goes_here','password_goes_here');
if (!$cxn)
    exit;
MysqL_select_db('your_database_name',$cxn);

// check if we can get hold of the form field
if (!post('my_value'))
    exit;

// let make sure we escape the data
$val = MysqL_real_escape_string(post('my_value'),$cxn);

// lets setup our insert query
$sql = sprintf("INSERT INTO %s (column_name_goes_here) VALUES '%s';",'table_name_goes_here',$val
);

// lets run our query
$result = MysqL_query($sql,$cxn);

// setup our response "object"
$resp = new stdClass();
$resp->success = false;
if($result) {
    $resp->success = true;
}

print json_encode($resp);
?>

请注意,这些都没有被测试.我希望它能帮助你.

原文地址:https://www.jb51.cc/php/132179.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐