大家好我需要你的帮助我是这个领域的新人 我已经创建了一个表单,我想在验证后使用php验证它 我想将它插入我的数据库,但验证没有用,请帮助我:(
const partialState$ = Rx.Observable.of(1).delay(0)
.publish().refCount();
答案 0 :(得分:0)
尝试这个
<?php
$fname = "";
$fnameErr = "";
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (empty($_POST['firstname'])) {
$fnameErr = "Firsname required";
}else{
$fname = test_input($_POST["firstname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
}
else{
mysql_connect('localhost','root','G0cl');
mysql_select_db('db') or die ('Unable to connect to database');
$insert_query = "INSERT into tbl values('$fname')" ;
$record_insert = mysql_query($insert_query);
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
include "process.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>practice</title>
</head>
<body>
<h2>Absolute classes registration</h2>
<form method = "post" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ?>">
<input type = "text" name = "firstname" placeholder=" Firsname ">
<span class = "error">* <?php echo $fnameErr;?></span>
<input type = "submit" name = "submit" value = "Submit">
</form>
</body>
</html>
您需要在preg_match之后包含插入查询代码。如果preg_match为false,则可以将firstname插入数据库表。
答案 1 :(得分:0)
您的代码为:
If POST:
Do validation.
Do database insert.
Display form (with errors/feedback).
换句话说,验证失败与否并不重要。
你想要逻辑:
If POST
Do validation
If no validation errors:
Do database insert.
If insert success:
Redirect.
Display form (with errors/feedback).
此处示例:
<?php
$errors = [];
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$firstname = isset($_POST['firstname']) ? trim($_POST['firstname']) : null;
if (empty($firstname)) {
$errors['firstname'] = "Firstname required.";
}
elseif (!preg_match("/^[a-zA-Z ]*$/", $firstname)) {
$errors['firstname'] = "Only letters and white space allowed.";
}
// etc.
if(! count($errors)) {
echo 'Passed validation, do database insert and then redirect here.';
}
}
$show_error = function($key) use ($errors) {
if(isset($errors[$key])) {
return '<span class = "error">*' . $errors[$key] . '</span>';
}
};
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<h2>Absolute beginners</h2>
<form method = "POST" action = "">
<input type = "text" name = "firstname" placeholder="e.g. Joe.">
<?= $show_error('firstname'); ?>
<input type = "submit" name = "submit" value = "Submit">
</form>
</body>
</html>