我有一系列电子邮件,我想通过验证我的数据库来检查所有这些电子邮件是否有效。我想将无效的电子邮件(如果有)添加到空数组中。我对 MySQL 不太熟悉,所以我需要一些帮助来做这件事。到目前为止,这是我的 PHP 文件中的内容:
<?php
$conn = mysqli_connect($servername, $username, $password, $db);
$conn->select_db($db);
if($conn->connect_error) {
die("Connection failed " . $conn->connect_error);
}
echo "Connected successfully\n";
$tags = preg_split("/\,/", $_POST['tags']);
$invalidEmails = array();
$count = 0;
$result = $conn->query("SELECT mail FROM dej_colleagues");
for ($i = 0; $i < sizeof($tags); $i++) {
$trim_brackets = trim($tags[$i], '[]');
$trim_quotes = trim($trim_brackets, '"');
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
if ($trim_quotes == $row["mail"]) {
$count += 1;
}
else {
array_push($invalidEmails, $tags[i]);
}
}
}
if (sizeof($tags) == $count) {
echo "good";
}
?>
我的数据库连接成功,但即使我的标签数组中的电子邮件存在于数据库中,它也不会检测到它。此外,数据库列有 10 万个条目,所以如果您知道更有效的方法,请告诉我。
答案 0 :(得分:2)
使用 WHERE IN
构建语句以获取匹配的邮件,然后比较结果数组会更有效。
您可以使用 array_diff()
来获取数组的差异。
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $db);
echo "Connected successfully\n";
$tags = preg_split("/\,/", $_POST['tags']);
$invalidEmails = array();
$count = 0;
// modify your array how you want it
foreach ($tags as $i => $tag) {
$trim_brackets = trim($tag, '[]');
$trim_quotes = trim($trim_brackets, '"');
$tags[$i] = $trim_quotes;
}
// build placeholders for WHERE IN
$in = str_repeat('?,', count($tags) - 1) . '?';
// prepare query
$stmt = $conn->prepare("SELECT mail FROM dej_colleagues WHERE mail IN ($in)");
// bind an array of values. First params is a type list.
$stmt->bind_param(str_repeat('s', count($tags)), ...$tags);
$stmt->execute();
$results = $stmt->get_result();
// fetch the matching mails into an array
$mails = [];
foreach ($results as $row) {
$mails[] = $row['mail'];
}
// get the difference between the two arrays
$invalidEmails = array_diff($tags, $mails);
if (count($tags) === count($mails)) {
echo "good";
}
var_dump($invalidEmails);
答案 1 :(得分:0)
问题很可能是一旦结果中没有更多行,mysqli_fetch_array
将返回 null。这意味着 for ($i = 0; $i < sizeof($tags); $i++)
循环第二次运行时,将找不到任何行,因此 while
循环不会再次运行。
您需要将 SQL 结果输出到一个常规的 PHP 数组中,这样您就可以重复遍历它们而不会出现此问题。
例如:
$result = $conn->query("SELECT mail FROM dej_colleagues");
$rows = mysqli_fetch_all($result, MYSQL_ASSOC);
for ($i = 0; $i < sizeof($tags); $i++) {
$trim_brackets = trim($tags[$i], '[]');
$trim_quotes = trim($trim_brackets, '"');
foreach ($rows as $row) {
if ($trim_quotes == $row["mail"]) {
$count += 1;
}
else {
array_push($invalidEmails, $tags[i]);
}
}
}
文档:https://www.php.net/manual/en/mysqli-result.fetch-all.php
注意可能有比这更有效的数据搜索方法,但这超出了我的回答范围。