我在下面的php代码中添加了 if ,我需要在mysql DB中检查条目是否存在。
if 语句中的变量为null且 else 不起作用,并保持回显空行。有什么想法吗?
<?php
include ('config/config.php');
$dir = '/home/masteryoda/certs';
$sql = "select * from certificates";
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if ($file != "." && $file != "..") {
$files = $dir."/".$file;
$data = openssl_x509_parse(file_get_contents($files));
$validFrom = date('Y-m-d', $data['validFrom_time_t']);
$validTo = date('Y-m-d', $data['validTo_time_t']);
$common = $data['subject']['CN'];
$issuer = $data['issuer']['CN'];
$res = $conn->query($sql);
while ($row = $res->fetch_assoc())
{
if ( $common == $row['CommonName'] && $validFrom == $row['ValidFrom'] && $validTo == $row['ValidTo'] )
{
echo "Vars:".$common."".$row['CommonName']."".$validFrom."".$row['ValidFrom']."".$validTo."".$row['ValidTo'];
echo "Certificate exists";
continue;
}
else
{
$result = $conn->query("insert into certificates (CommonName,ValidTo,ValidFrom,Issuer) values ('$common','$validTo','$validFrom','$issuer')");
}
}
}
}
closedir($dh);
}
}
答案 0 :(得分:-1)
尝试使用!empty()函数。
if (!empty($row)) {
echo "Vars:" . $common . "" . $row['CommonName'] . "" . $validFrom . "" . $row['ValidFrom'] . "" . $validTo . "" . $row['ValidTo'];
echo "Certificate exists";
} else {
$result = $conn->query("insert into certificates (CommonName,ValidTo,ValidFrom,Issuer) values ('$common','$validTo','$validFrom','$issuer')");
}