2014-01-15 46 views
0

我希望實現正則表達式作爲檢查用戶輸入的一種方式,並且在查看本文後(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> 
+1

我的第一個問題:你懂的正則表達式做什麼?你能讀一下嗎?你能保持它嗎? –

+2

這個問題似乎是無關緊要的,因爲開瓶器必須證明對待解決問題的最小理解 – hek2mgl

+0

看起來像。他只是複製了這些代碼,但不能讀取它。我的建議:使用對於初學者來說容易理解的方法,最好的方法是字符串函數。 http://php.net/manual/en/ref.strings.php如果你不知道如何處理正則表達式,它毫無意義地給你任何有關它的建議。每個經驗豐富的RegExer都會看到這個錯誤,但是如果您無法親自看到它,您將永遠無法學習。 –

回答

0

你的正則表達式似乎沒問題。

你的問題是,你需要在發佈前檢查錯誤/插入到數據庫..事情是這樣的:

if (count($errors) > 0) { 
    // prepare and execute sql insert here. 
} 
+0

@YU NO WORK,@ MElliott謝謝,這是我理解正則表達式的實現邏輯時缺失的一個鏈接,我實現了這個 if(empty($ reg_errors)) {//在這裏準備和執行sql insert。}在發佈之前檢查錯誤,我的驗證系統按預期工作。 – Terungwa

+0

@MichelMzer - 非常好!很高興我能幫上忙!如果您發現此問題爲答案或有助於解決您的問題,請接受答案或同意或兩者兼而有之,謝謝。 :) – MElliott