我编写了这段代码,用于将表单中的数据添加到数据库中。那部分有效。
我尝试在成功添加数据后将页面重定向到completed.php
。现在它只将数据添加到我的数据库表中,仅此而已。
这是我的代码:
<html>
<head>
<title>insert data in database using PDO(php data object)</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using PDO</h1>
<div id="login">
<h2>Student's Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="username" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="email" id="email" required="required" placeholder="john123@gmail.com"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
<?php
if(isset($_POST["submit"])){
$hostname='localhost';
$username='adendud85_root';
$password='ayebruh';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=adendud85_aye",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO aye (username, email)
VALUES ('".$_POST["username"]."','".$_POST["email"]."')";
if ($dbh->query($sql)) {
//echo "Success";
header("Location: completed.php?username=".$_POST["username"]."");
}
else{
echo "error";
}
$dbh = null;
}
catch(PDOException $e)
{
echo "error";
}
}
?>
</body>
</html>
任何人都知道该做什么或做错了什么?
答案 0 :(得分:0)
这样,你的所有echo语句应该在标题之后。
<?php
if(isset($_POST["submit"])){
$hostname='localhost';
$username='adendud85_root';
$password='ayebruh';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=adendud85_aye",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO aye (username, email)
VALUES ('".$_POST["username"]."','".$_POST["email"]."')";
if ($dbh->query($sql))
{
header("Location: completed.php?username=".$_POST["username"]);
//echo "Success";
}
else{
echo "error";
}
$dbh = null;
}
catch(PDOException $e)
{
echo "error";
}
}
?>
<html>
<head>
<title>insert data in database using PDO(php data object)</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="main">
<h1>Insert data into database using PDO</h1>
<div id="login">
<h2>Student's Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="username" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="email" id="email" required="required" placeholder="john123@gmail.com"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
</body>
</html>
另外,请使用prepared
语句。