我正在尝试在 txt 文件的一行中搜索字符串,包含我正在搜索的字符串的行必须插入到我的数据库中。
php while 循环遍历所有行,就像我说的,我正在尝试将它找到的行插入到我的数据库中。
现在的问题是,如果我运行此代码,它会将所有 txt 文件插入我的数据库中,我不明白为什么。
$search = $_GET["search"];
$logfile = $_GET['logfile'];
// Read from file
$file = fopen($logfile, "r");
?>
<head> <title>Searching: <?php echo $search ?></title> </head>
<?php
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search))
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(stristr($line,$search))
$sql = "INSERT INTO `ingamebanlist` (Ban, Timestamp) VALUES ('$line', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
// case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
fclose($file);
有不懂的地方请追问
最佳答案
这很可能是因为您没有构建代码。罪魁祸首是这样的检查:
if(stristr($line,$search))
$servername = "localhost";
if
只是屏蔽下面的行。您应该将代码块括在 {
和 }
中,以便仅在匹配时有条件地运行它们。您在制作 $sql=
查询时做了同样的事情。尽管插入时应该只是将前面的行加倍。
您确实应该将 mysqli 连接代码移出循环。提前做一次。
顺便说一句,读取和过滤输入的更紧凑的方式是:
$f = new SplFileObject("logfile.txt", "r");
$f = new RegexIterator($f, "/" . preg_quote($search, "/") . "/i");
foreach ($f as $line) {
db::insert(...);
}
关于php - 过滤掉TXT中的行并插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28127879/