从 PHP (jQuery/AJAX) 插入 MySQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5143191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting into MySQL from PHP (jQuery/AJAX)
提问by Simon H
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.
我看过很多教程,但它们太令人困惑了,为了做我想做的事,我只是不知道如何使用这些教程中的现有内容并让它们按照我希望的方式工作。
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.
我有一个非常简单的表单,包含一个文本框、标签和一个提交按钮。当用户在表单中输入内容,然后单击提交时,我想使用 php 和 ajax(使用 jquery)将表单的结果插入到 mysql 数据库中。
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.
有人可以告诉我这是如何实现的吗?我所追求的只是一些非常基本的东西,让我开始。任何帮助表示赞赏。
Thank you
谢谢
回答by Simon H
Hi here is just a quick example of how one might do it:
嗨,这里只是一个简单的例子,说明如何做到这一点:
The HTML:
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>
The process.php script:
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);
?>
Please note that none of this has been tested. I hope it helps you thou.
请注意,这些都没有经过测试。我希望它对你有帮助。
回答by mario
The jQuery part is often quite simple. It just redirects the ordinary form action= over a Javascript handler. $.post
is easy to use and you just need .serialize()
to package up the existing form values into a string:
jQuery 部分通常非常简单。它只是通过 Javascript 处理程序重定向普通表单 action=。$.post
易于使用,您只需.serialize()
要将现有的表单值打包成一个字符串:
<form id="example">
<input name="textbox" ...>
<input type=submit name="submitbuttonname" value="submit"
onClick="$.post('save.php', $('form#example').serialize())">
And on PHP side you simply receive the content via $_POST
and save it to the database (using the old mysql_ functions would also be possible, just more cumbersome):
在 PHP 方面,您只需通过以下方式接收内容$_POST
并将其保存到数据库中(使用旧的 mysql_ 函数也是可能的,只是更麻烦):
$db = new PDO("mysql:...");
if ($_POST["submitbuttonname"]) {
$q = $db->prepare("INSERT INTO save (textbox, label) VALUES (?, ?)";
$q->execute(array($_POST["textbox"], $_POST["label"]));