我在验证数组中的值的脚本时遇到困难,验证后它会检查列中是否已存在这些值,如果没有重复,则应将这些值添加到数据库中,每个值添加到相应的列中.
我尝试了很多方法,最接近的是检查数组中的一个值是否已存在于表的 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=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();
}
}
}
最佳答案
这是基于您的代码。
最多允许输入 5 个电子邮件。它验证它们并显示单独的错误消息。它可以防止在表单中输入重复的电子邮件。
针对输入的列数生成数据库查询。
数组:$emailDetails 保存有关各个电子邮件的所有信息。
测试:strlen(implode($_POST['email']) 确保输入数组中至少有一个值。
测试: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));
?>
关于php - 检查数组中的值是否已存在于数据库中+将数组添加到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22885105/