【发布时间】:2020-06-16 06:08:45
【问题描述】:
我正在尝试创建一个管理员可以同时将多个人添加到数据库中的系统。我希望这个系统能够阻止管理员添加具有数据库中已经存在的电子邮件地址的人员。
如果 _POST["emailaddress"] 中的一封电子邮件与数据库中的其中一个电子邮件地址匹配,用户应该收到一条消息,说明其中一封电子邮件已存在于数据库中。为此,我尝试使用函数 array_intersect()。但是,这样做后,我会收到一条警告:
警告:array_intersect(): Argument #2 is not a array in ...addingusers.php on line 41
起初我认为这与我的第二个参数是关联数组这一事实有关,所以我尝试了函数 array_intersect_assoc,它返回相同的警告。我该如何解决这个问题?
addingusers.php
上的代码<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
//amount of emailaddresses in db
$checkquery2 = mysqli_query($conn, "
SELECT COUNT(emailaddress)
FROM users
");
$result2 = mysqli_fetch_array($checkquery2);
// the previously mentioned amount is used here below
for($i=0; $i<$result2[0]; $i++){
// the actual emails in the db itself
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1;
}
$query1 = $result_array1[$i]["emailaddress"];
}
// HERE LIES THE ISSUE
for($i=0; $i<count($emailaddress); $i++){
if (count(array_intersect_assoc($emailaddress, $query1)) > 0) {
echo "One of the entered emails already exists in the database...";
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
}
编辑 正如 cmets 所指出的, $query1 确实不是一个数组,它是一个字符串。但是,即使我删除了索引和“[emailaddress]”,问题仍然存在,例如,代码总是选择 else 语句而不是 if。
【问题讨论】:
-
基于
$query1 = $result_array1[$i]["emailaddress"];在我看来$query1将是一个字符串 -
$query1不是数组。这是最后一个用户的电子邮件地址,所以它是一个字符串。 -
你为什么要循环查询
SELECT emailaddress FROM users? -
@Don'tPanic 是的,但是当我忽略 "[$i]["emailaddress"]" 时,它总是选择 else ...
-
每次调用中添加了多少个地址(10 个,1000 个)?
标签: php array-intersect