我想要一个带有php的表单。但是好几个小时我都遇到了错误,错误是当$ _POST = [' name']想要被检查为空或不是空的时候。 当我检查数据库时,行是白色的,没有任何东西。 为了检查$ _POST是否为空,我打印出单词' empty'要确定它是空的,它将被打印出来并且是空的&#39 ;; 我的错误在哪里,它与数据库mysql有关,还是只与代码有关? 请帮助我,我感到困惑和无聊。 这是我的全部代码:
<!doctype html>
<html lang="fa">
<head>
<meta charset="utf-8">
<title>form</title>
<link href="addContact.css" rel="stylesheet"/>
<link href="main.css" rel="stylesheet"/>
<link href="table.css" rel="stylesheet"/>
</head>
<body>
<?php
$name = "";
$nameErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
echo 'empty';
$nameErr = "Name is required";
} else {
echo 'full';
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
$servername = "localhost";
$username = "abc";
$password = "abc";
$dbname = "abc";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO abc (firstname)
VALUES ('$name')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
提前谢谢
答案 0 :(得分:0)
问题在于使用empty()
您可以在变量上使用它,而不是在值上使用它。
请参阅此处查看PHP documentation page。
要检查此项,请先将其保存在另一个变量中,然后检查:
$tempVal = $_POST["name"];
if (empty($tempVal))
答案 1 :(得分:0)