2014-04-05 133 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

相關問題