사용자 입력을 검사하는 방법으로 정규 표현식을 구현하고이 게시물 (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>
내 첫 번째 질문 : 당신도 정규식이 무엇을 이해합니까? 읽을 수 있니? 그것을 유지할 수 있습니까? –
오프너가 해결해야 할 문제에 대해 최소한의 이해를 보여 주어야하기 때문에이 질문은 논외의 것으로 보입니다 – hek2mgl
처럼 보입니다. 그는 방금 그 코드를 복사했지만 읽을 수는 없습니다. 내 충고 : 초보자가 이해하기 쉬운 방법을 사용하십시오. 가장 좋은 방법은 문자열 기능입니다. http://php.net/manual/en/ref.strings.php Regex를 다루는 방법을 모른다면, 그 말을 듣지 않아도됩니다. 숙련 된 모든 RegExer는 실수를 본다. 그러나 독자적으로 그것을 볼 수 없다면 결코 배울 수 없을 것이다. –