Question

Im having difficulties with a script that validates values in an array, after the validation it checks if the values already exists in the columns and if there is no duplicate then the values should be added to the database, each to the corresponding column.

I've tried a lot of things and the closest i got was checking if one value in the array already existed in 1 column of the table. The script should check for duplicates in 5 columns of 1 table.

This is what i allready have written out:

    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>";
        }


//}

}}

And i think this is how i should add my array to a database:

$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;
        } 

If i should provide more information to clarify thinks let me know. Thanks in advance.

So with help of Ryan's answer i managed to add the array values to the database, i also managed to validate each value in the array. If one of the values in the arrays is not an emailadres they dont get inserted into the database, otherwise the values in the array will be inserted in the database. The remaining problem is that i dont know how to check for duplicates in the table. The table has 5 columns and for each value in the array it should be checked whether a duplicate exists in the table. Im going to continue to find the solution, any help or push in the right direction is greatly appreciated. my code: $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();
        } 
}
}
Was it helpful?

Solution

This is based on your code.

It allows up to 5 emails to be entered. It validates them and displays individual error messages. It prevents duplicate emails being entered on the form.

The database query is generated for as many columns as are input.

The array: $emailDetails holds all the information about the individual emails.

the test: strlen(implode($_POST['email']) ensures that the input array has at least one value in it.

Tested: 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));
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top