的index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<body>
<form id="myform" action="userinfo.php" method="post" >
Name: <input type="test" name="name" autofocus>
Age: <input type="text" name="age" >
<button id="sub"> save</button>
</form>
<span id="result"></span>
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>
my_script.js:
$("#sub").click( function() {
$.post( $("#myform").attr("action"),
$("#myform :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
$("#myform").submit( function() {
return false;
});
function clearInput() {
$("#myform :input").each( function() {
$(this).val('');
});
db.php中:
<?php
$conn = mysql_connect('localhost','B00556019','73eKESV3') ;
$db = mysql_select_db('b00556019');
?>
userinfo.php:
<?php
include_once('db.php');
$name = $_POST['name'];
$age = $_POST['age'];
if(mysql_query("INSERT INTO user (name, age) VALUES (
'$name','$age')";))
echo "Successful";
else
echo "insertion failed";
?>
它不会发布到数据库
数据库名称:b00556019
表:用户
fields:name(varchar,15)。年龄(INT,3)
除了userinfo页面显示为空白之外没有任何反应。
任何有关如何发布到数据库的建议的人都会很棒,如果有人有一个简单的教程,因为这是一个基本的教程,但仍然没有工作。
答案 0 :(得分:1)
旁注:按照目前的情况,您可以SQL injection
请考虑切换到使用mysqli_*
函数以及预准备语句或PDO。 mysql_*
函数已弃用,将从以后的PHP版本中删除。
而不是:
if(mysql_query("INSERT INTO user (name, age) VALUES (
'$name','$age')";))
echo "Successful";
else
echo "insertion failed";
使用:
$name = mysql_real_escape_string($_POST['name']);
$age = mysql_real_escape_string($_POST['age']);
$result = mysql_query("INSERT INTO user (name, age) VALUES ('$name','$age')");
if(!mysql_query($result)){
echo "Insertion was not successful.";
} else {
echo "Insertion was successful.";
}
您可能还需要传递数据库连接:
if(!mysql_query($result,$conn))
准备好的陈述方法:
$conn = new mysqli("xxx", "xxx", "xxx", "xxx");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$name = $_POST['name'];
$age = $_POST['age'];
$result = $conn->prepare("INSERT INTO user (name, age) VALUES (?,?)");
$result->bind_param("ss", $name, $age);
$result->execute();
$result->close();
// If there is any error with your SQL statement an
// error is thrown and displayed to the user:
printf("Prepared Statement Error: %s\n", $conn->error);
答案 1 :(得分:0)
首先纠正表名:&#34; table:users&#34;它是&#34;用户&#34;你在代码中使用过。
if(!$conn){
echo mysql_error() ; // first check while connecting..
}
// on the insertion code .....
if(mysql_query("INSERT INTO user (name, age) VALUES (
'$name','$age')";))
echo "Successful";
else
echo mysql_error($conn) ; // you will see what is the error..
echo "insertion failed";