我试图通过php在数据库中插入html表单数据。 我无法将html表单数据插入数据库,我不知道我的代码中出错了什么?
这是我的代码:
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'mydb';
$con=mysqli_connect($host, $username, $password,$dbname);
if (!$con)
{
echo "connection failed";
}
if(isset($_POST['submit']))
{
$name = $_POST['username'];
$pass = $_POST['password'];
$sql="insert into mytable1 (name,password) VALUES ('$name', '$pass')";
if(mysqli_query($con,$sql))
{
echo "DATA IS INSERTED INTO DATABASE";
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>SignUpform.com</title>
</head>
<body>
<div id="div1">
<div id="div2">
<h1>Sign up Form</h1>
</div>
<form action="" method="post">
<fieldset>
<legend>Signup form ceredentials</legend>
<p id="p1">Name:</p>
<input id="text1" type="text" placeholder="Enter username" name="username">
<p id="p2">Password:</p>
<input id="pass1" type="password" placeholder="Enter Password" name="password">
<p id="email">Email:</p>
<input id="emailtextfld" type="text" placeholder="Enter Email" name="email">
<p id="company">Company Name:</p>
<input id="companytextfld" type="text" placeholder="Company name" name="company">
<input id="donebtn" type="submit" value="submit" name="submit">
</fieldset>
</form>
</div>
</body>
</html>
答案 0 :(得分:2)
if(isset($_POST['submit']))
{
$name = $_POST['username'];
$pass = $_POST['password'];
$sql="insert into mytable1 (name,password) VALUES ('$name', '$pass')";
$query = mysqli_query($con, $sql);
if($query)
{
echo "<h4 style='color:green'>Inserted Successfully.</h4>";
}
else
{
echo "<h4 style='color:red'>Faild.</h4>";
}
}
?>
尝试此解决方案。
答案 1 :(得分:2)
您应该从以下位置更改数据库的存储引擎:
ENGINE=MRG_MyISAM DEFAULT CHARSET=utf8mb4;
到
ENGINE=innoDB DEFAULT CHARSET=utf8;
从我的观点来看,这只是因为“引擎错误”而发生的。因此,在更改了数据库的存储引擎之后,我希望它能为你的inshallah工作。
答案 2 :(得分:1)
您需要像这样进行表单操作
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
添加此项以检查连接
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}