1

我有一个表单,用户在其中插入他们的姓名,一旦他们提交表单,页面应该检查提供的名称是否已经存在,如果存在,应该返回错误,否则,正常进行。

如何检查我的输入值是否存在,如果存在则停止表单?

<?php

$array = get_meta_values( 'user_submit_name' );
// Array to search:
// Temp array so we don't find the same key multipule times:
$temp = array();
// Iterate through the array:
foreach ($array as $key)
{
// Check the key hasn't already been found:
if (!in_array($key, $temp))
{
    // Get an array of all the positions of the key:
    $keys = array_keys($array, $key);
    // Check if there is more than one position:
    if (count($keys)>0)
    {
        // Add the key to the temp array so its not found again:
        $temp[] = $key;
        // Do something...
        echo '<li>Name already used';                        
    }
}
}
?>

html

<form class="form-horizontal" role="form" id="usp_form" method="post" data-validate="parsley" enctype="multipart/form-data" novalidate>

        <div class="form-group">
            <label  class="col-lg-2 control-label" for="user-submitted-name">Il tuo nome</label>
             <div class="col-lg-10">
                <input name="user-submitted-name" type="text" value="" data-required="true" required placeholder="Your name" class="form-control input-lg usp-input">
            </div>
        </div>

    <div class="form-group">
         <div class="col-lg-offset-2 col-lg-10">
            <input class="submit btn btn-lg btn-primary" name="user-submitted-post" id="user-submitted-post" type="submit" value="<?php _e('Submit', 'usp'); ?>">
        </div>
    </div>
4

2 回答 2

1

我从您的评论中得知您有以下内容:

$_POST["user-submitted-name"]; // name from the form
$names = get_meta_values('user_submit_name'); // array with names not allowed

然后它看起来像简单的方法:

if (in_array($_POST["user-submitted-name"], $names)) {
    // posting not allowed
    echo '<li>Name already used';
} else {
    // posting is allowed
    // save posting here...
    // and then go to success page:
    header("Location: success.html"); // redirect
    exit(); // and stop here
}
于 2013-09-15T19:22:01.613 回答
0

只需使用多级break语句并退出循环即可。

就像是

if (count($keys)>0)
    {
        // Add the key to the temp array so its not found again:
        $temp[] = $key;
        // Do something...
        echo '<li>Name already used';  
        break 3;                      
    }
于 2013-09-15T18:54:04.650 回答