2014-04-05 144 views
0

Im在验证数组中的值时检查数组中的值是否存在困难,并检查列中是否已存在值,如果没有重复值应该添加到数据库中,每个值都添加到相应的列中。检查数组中的值是否已经存在于数据库中+将数组添加到数据库中

我已经尝试了很多东西,最近我得到的是检查数组中的一个值是否已经存在于表的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的回答帮助下,我设法将数组值添加到数据库中,我也设法验证数组中的每个值。如果数组中的某个值不是emailadres,则不会插入数据库,否则数组中的值将插入到数据库中。剩下的问题是我不知道如何检查表中的重复项。该表有5列,对于数组中的每个值,应检查表中是否存在重复。我将继续寻找解决方案,任何帮助或推动正确的方向非常感谢。我的代码: $ i = 0; $ j = count($ _ POST ['email']);

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(); 
     } 
} 
} 
+0

旁注:使用'
'而不是'
'很多人犯了这个错误。 –

+1

是的,我看到了,谢谢! – Avuerro

+0

我将添加代码来检查重复项目:-)我会发布另一条评论,当我添加并检查码。如果您发现它有用,请记得稍后再接受该答案。 –

回答

0

这是基于你的代码。

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

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

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

测试:strlen的(内爆($ _ POST [ '电子邮件'])确保了输入阵列具有在它的至少一个值

测试:。PHP 5.3.18视窗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)); 
?> 
+0

谢谢,您提供的代码中有一部分解决方案。只有我仍然在努力检查重复。 – Avuerro

相关问题