我希望实现正则表达式作为检查用户输入的方法,并在审阅此帖子后Issue on Using Regular Expression in PHP Simple Validation)我想出了下面的代码。当我运行我的脚本并输入名字和姓氏的数字时,无论我的正则表达式如何,它们都会成功发布。我想知道我在这里做错了什么。
<?php
$errors = array();
// ....create database connection.....//
if (isset($_POST['insert'])) {
$last_name = trim($_POST['last_name']);
$first_name = trim($_POST['first_name']);
$age = trim($_POST['age']);
// ....My regular expressions.....//
if(isset($_POST['last_name'])){
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST['last_name']) === 0) {
$errors[] = 'lastname should not contain spaces.'; }
}
if(isset($_POST['first_name'])){
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST['first_name']) === 0) {
$errors[] = 'firstname should not contain spaces.';}
}
$OK = false;
$stmt = $conn->stmt_init();
$sql = 'INSERT INTO voter_tracking (
v_id,
last_name,
first_name,)
VALUES(?, ?,?)';
if ($stmt->prepare($sql)) {
$stmt->bind_param('iss', $_POST['v_id'], $_POST['last_name'], $_POST['first_name']);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$OK = true;
}
// redirect if successful or display error
if ($OK) {
echo 'posted';
exit;
} else {
$error = $stmt->error;
}}}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
</head>
<body>
<div id="main">
<fieldset>
<legend><h2>Add New Voter Record:</h2></legend>
<?php if (isset($error)) {
echo "<p class=\"warning\">Error: $error</p>";
} ?>
<form id="form1" method="post" action="">
<p>
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" class="widebox" id="name" required aria-required="true">
</p>
<p>
<label for="first_name">First Name:</label>
<input type="text" name="first_name" class="widebox" id="first_name" required aria-required="true">
</p>
<p>
<input type="submit" name="insert" value="Insert New Entry" id="insert">
</p>
</form>
</fieldset>
</div>
</body>
</html>
答案 0 :(得分:0)
你的正则表达式似乎没问题。
您的问题是您需要在发布/插入数据库之前检查错误。这样的事情:
if (count($errors) > 0) {
// prepare and execute sql insert here.
}