插入到MySQL从PHP(jQuery的/ AJAX)
我看过很多教程,但他们是如此的混乱,做我想做的事情,我只是不明白如何利用现有的东西,从这些教程,使他们的工作,他们的方式我希望他们。
I have seen many tutorials, but they're so confusing, and to do what I want to do, I just don't get how to use existing stuff from those tutorials and make them work they way I want them to.
我有一个非常简单的形式,包含一个文本框,标签和一个提交按钮。当用户输入一些东西到表单,然后点击提交,我想用PHP和AJAX(使用jQuery)插入表单结果到MySQL数据库中。
I have a very simple form, containing a textbox, label and a submit button. When the user enters something into the form, then clicks submit, I would like to use php and ajax (with jquery) to insert the result of the form into a mysql database.
是否有人可以告诉我怎么能做到这一点?只是一些非常基本都是让我开始之后,我是。任何帮助是AP preciated。
Can someone please show me how this can be achieved? Just something very basic is all i'm after to get me started. Any help is appreciated.
感谢您
你好这里是怎么一会做它只是一个简单的例子:
Hi here is just a quick example of how one might do it:
中的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脚本:
The process.php script:
<?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);
?>
请注意,这一切都不进行了测试。我希望它可以帮助你你。
Please note that none of this has been tested. I hope it helps you thou.