检查数据库中的值是否已存在于数据库中+数组添加数组

时间:2014-04-05 18:38:12

标签: php mysql sql dynamic-arrays

我遇到了验证数组中值的脚本有困难,验证后它会检查列中是否已存在值,如果没有重复则应将值添加到数据库中,每个值都添加到相应的列中

我已经尝试了很多东西,我得到的最接近的是检查数组中的一个值是否已存在于表的1列中。该脚本应检查1个表的5列中的重复项。

这是我已经写出来的:

    foreach ($_POST['email'] as $value){

if(! filter_var($value, FILTER_VALIDATE_EMAIL))
{

    echo "</br>" . $value;
    echo "</br> email invalid</br>";
}
else {

    try{
        $DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
        //foreach($_POST['email'] as $value){
            //echo "</br> $value </br>";
        $query =  "SELECT * FROM uitnodigen WHERE email = :email " ;
        $stmt = $DB->prepare($query);
        $stmt->bindParam(':email', $value);
        $blaa = $stmt->rowCount();
        $stmt->execute();

                }
                catch (PDOException $exception){
                    printf($exception->getMessage());
                }
                echo "</br> </br>  $value </br></br>";
                echo " $blaa";
                    if($stmt->rowCount() > 0)
            {   echo "email exists";

            }
                else {

        echo "</br>ok </br>";
        }


//}

}}

我认为这是我应该如何将我的数组添加到数据库中:

$columns= implode(",", array_keys($_POST['email']));
$value= implode(",", array_values($_POST['email']));
echo "</br>$columns</br>";
echo "</br> $value </br>";
/*
foreach ($_POST['email'] as $value){*/
try{
    $DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);

$query="INSERT INTO `uitnodigen` (`0` , `1` , `2 `, `3 `, `4`) VALUES ($value)";
$stmt = $DB->prepare($query);
$stmt->execute();}
catch(PDOException $e){
            echo $e;
        } 

如果我应该提供更多信息来澄清,请告诉我。提前谢谢。

所以在Ryan回答的帮助下,我设法将数组值添加到数据库中,我还设法验证了数组中的每个值。如果数组中的某个值不是电子邮件,则它们不会插入到数据库中,否则数组中的值将插入数据库中。剩下的问题是我不知道如何检查表中的重复项。该表有5列,对于数组中的每个值,应检查表中是否存在重复。我将继续寻找解决方案,任何帮助或推动正确的方向非常感谢。 我的代码:     $ I = 0;     $ J =计数($ _ POST [ '电子邮件']);

foreach ($_POST['email'] as $value){
    $i++;   
if(! filter_var($value, FILTER_VALIDATE_EMAIL))
{

    echo "<br />email invalid<br />";


}
elseif($j==$i){
    $emailQueryValues = array(  ':email0' => $_POST['email']['0'],
                                ':email1' => $_POST['email']['1'],
                                ':email2' => $_POST['email']['2'],
                                ':email3' => $_POST['email']['3'],
                                ':email4' => $_POST['email']['4']);
    echo "email klopt</br>"; 
    $sql = 'insert into uitnodigen (`email0`, `email1`, `email2`, `email3`, `email4`) '
      .' values (:email0, :email1, :email2, :email3, :email4)';
try{
    $DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$query = $DB->prepare($sql);
$query->execute($emailQueryValues);
}
catch(PDOException $e){
            echo $e->getMessage();
        } 
}
}

1 个答案:

答案 0 :(得分:0)

这取决于您的代码。

最多可输入5封电子邮件。它验证它们并显示各个错误消息。它可以防止在表单上输入重复的电子邮件。

为输入的列数生成数据库查询。

数组:$ emailDetails包含有关各个电子邮件的所有信息。

测试:strlen(implode($ _ POST [&#39; email&#39;])确保输入数组中至少有一个值。

经测试:PHP 5.3.18 windows XP。

<?php // Q22885105 - example tested code.
/*
 * this is an example of how to generate the query and the bind values...
 *
 * You will need to modify it for your use case.
 *
 * This script allows 5 'email' to be entered and stored
 */

/*
 * Do we have some email input? -- do some validation
 */
$badEmailCount = 0; // assume all the 'email' are correct

$emailDetails = array(); // store email info in here
                         // use $emailDetails['isValid'][0]  - to check if all ok!
                         // use $emailDetails['value'][0]    -  to get the value
                         //
// let us make life easier for us all and ensure that there are always 5 'email'!
    for($idx = 0; $idx < 5; $idx++) {
        $emailDetails['isValid'][$idx] = TRUE; // must be true!
        $emailDetails['value'][$idx]   = '';
        $emailDetails['htmlId'][$idx]  = "email_$idx";
        $emailDetails['colName'][$idx] = "email$idx";
        $emailDetails['error'][$idx]   = "";

    }

if (!empty($_POST['email']) && strlen(implode($_POST['email'])) >= 1) { // validate email input

    for($idx = 0; $idx < 5; $idx++) {

        if (!empty($_POST['email'][$idx])) {
            $isBad = !filter_var($_POST['email'][$idx], FILTER_VALIDATE_EMAIL);


            if ($isBad) {
                $emailDetails['error'][$idx] = 'is bad email address';
            }
            else { // duplicate check
                foreach($_POST['email'] as $idxDup => $dupValue) {
                    $isBad =  $idxDup !== $idx && $dupValue == $_POST['email'][$idx];

                    if ($isBad) {
                        $emailDetails['error'][$idx] = 'is duplicated email address';
                        break;
                    }
                }
            }

            if ($isBad) {
                $badEmailCount++;
            }

            $emailDetails['isValid'][$idx] = !$isBad;
            $emailDetails['value'][$idx]   = $_POST['email'][$idx];
        }
    }
}
else { // do we have the form but is it empty?
    if (!empty($_POST['email'])  && strlen(implode($_POST['email'])) == 0) {
        $emailDetails['isValid'][0] = false;
        $emailDetails['error'][0] = 'one email address is needed';
        $badEmailCount++;
    }
} // end validation...
?>
<!-- generate HTML code for the email form -->
<?php if (empty($_POST['goEmail']) || $badEmailCount > 0): // no input or has error -  show the form... ?>
<form action="" method="post"
   <fieldset class="email">
       <legend>Email details please...</legend>
         <?php for($idx = 0; $idx < 5; $idx++): ?>

        <div style="margin: 2px;<?php echo !$emailDetails['isValid'][$idx] ? ' border: 2px solid red;' : '';?> ">
            <label for id="<?php echo $emailDetails['htmlId'][$idx]?>"><?php echo $emailDetails['colName'][$idx]?></label>

            <input type="text" name="email[]" id="<?php echo $emailDetails['htmlId'][$idx]?>"
                    value="<?php echo $emailDetails['value'][$idx]  ?>">

            <?php echo !$emailDetails['isValid'][$idx] ? $emailDetails['error'][$idx] : ''; ?>
         </div>
         <?php endfor; ?>
    </fieldset>
    <input type="submit" name="goEmail" value="tell us your thoughts...">

</form>
<?php endif; ?>

<?php
if (empty($_POST['goEmail']) || $badEmailCount > 0) {
   exit; // leave the script now...
}

// continue processing the input data

// database connection...
$dsn = 'mysql:host=localhost;dbname=testmysql';
$username = 'test';
$password = 'test';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$theDB = new PDO($dsn, $username, $password, $options);

// make db/pdo throw an exception when it gets confused.
$theDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// ------------------ end of database connection --------


// get input form details...
$emailQueryValues  = array();

$sqlColumns  = '';
$sqlBindings = '';

for($idx = 0; $idx < 5; $idx++) {
    if (!empty($emailDetails['value'][$idx])) {
        $sqlColumns  .= '`'. $emailDetails['colName'][$idx] .'`,';
        $sqlBindings .= ':'. $emailDetails['colName'][$idx] .',';

        $emailQueryValues[':'. $emailDetails['colName'][$idx]] = $emailDetails['value'][$idx];
    }
}
$sqlColumns  = rtrim($sqlColumns, ', '); // lose trailing comma
$sqlBindings = rtrim($sqlBindings, ', ');


try {
    $sql = "insert into uitnodigen ($sqlColumns) values ($sqlBindings)";
    $query = $theDB->prepare($sql);
    $query->execute($emailQueryValues);
    $lastId = $theDB->lastInsertId();
}
catch (\Exception $e) {
    echo 'drat! '. $e->getMessage();
    // throw $e; // re-raise the exception
}

// test it worked...
$sql = 'select * from uitnodigen where id = :id';
$query = $theDB->prepare($sql);
$query->execute(array(':id' => $lastId));
$resultSet = $query->fetchAll();
var_dump(current($resultSet));
?>