我编写了PHP代码来向我的数据库添加记录。当我点击保存按钮时,它应该说“已成功保存”,但所有发生的情况是页面刷新而数据库中没有添加记录,并且没有弹出“已保存成功”消息。
我的数据库连接正常。所以我无法弄清问题是什么。
这是PHP代码:
<?php
error_reporting(0);
$con = mysqli_connect("localhost", "root", "password") or die("error");
if($con) {
mysqli_select_db("maplibrary",$con);
}
if (isset($_POST["save"])) {
$sql = mysqli_query("INSERT INTO member (memberID, firstName, surname, contactDetails)
VALUES('{$_POST['memberID']}',
'{$_POST['firstName']}',
'{$_POST['surname']}',
'{$_POST['contactDetails']}'
)");
if ($sql) {
echo "save successfully";
}
}
?>
这是HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>ViewMembers</title>
</head>
<body>
<form action="" method="post">
<table style="border:1 #F00 solid;width:500px;overflow:auto;margin:auto;background:#999;">
<tr>
<td>Member ID</td>
<td><input type="text" name"memberID" /></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name"firstName" /></td>
</tr>
<tr>
<td>Surname</td>
<td><input type="text" name"surname" /></td>
</tr>
<tr>
<td>Contact Details</td>
<td><input type="text" name"contactDetails" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" name="save" /></td>
</tr>
</table>
</form>
</body>
</html>
答案 0 :(得分:0)
您没有添加 $ conn 作为mysqli_query函数的参数。参见用法: http://www.w3schools.com/php/func_mysqli_query.asp
<?php
error_reporting(0);
$con = mysqli_connect("localhost","root","password") or die("error");
if($con)
{
mysqli_select_db("maplibrary",$con);
}
if (isset($_POST["save"]))
{
$sql = mysqli_query($con, "INSERT INTO member
(memberID,firstName,surname,contactDetails)
VALUES('{$_POST['memberID']}',
'{$_POST['firstName']}',
'{$_POST['surname']}',
'{$_POST['contactDetails']}'
)");
if ($sql)
{
echo "save successfully";
}
}
?>
答案 1 :(得分:0)
试试这个:
<?php
$servername = "localhost";
$username = "username";//YOUR USER NAME!
$password = "password";//YOUR PASSWORD!
$dbname = "myDB"; //YOUR DB NAME!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["save"])){
$var1 = $_POST['memberID'];
$var2 = $_POST['firstName'];
$var3 = $_POST['surname'];
$var4 = $_POST['contactDetails'];
$sql = "INSERT INTO member(memberID,firstName,surname,contactDetails)
VALUES ('".$var1."', '".$var2."', '"$var3."', '"$var4."')";
if ($conn->query($sql) === TRUE) {echo "successfully saved";}
else {echo "Error: " . $sql . "<br>" . $conn->error;}
}
$conn->close();
?>
希望我理解你的问题...... :) 顺便说一句,我建议你创建一个只包含连接的php文件,因为你可能需要在某些时候再次连接到数据库,所以你不想一次又一次地复制代码...... 所以你可以创建一个只包含连接线的connect.php,你可以在任何你想要的页面中包含它(connect.php)。它将使套件更容易。 看看:php include