Php 过滤出TXT中的行并插入数据库
我试图在txt文件的一行中搜索字符串,包含我正在搜索的字符串的行必须插入到我的数据库中 php在遍历所有行时,正如我所说,我正在尝试将它找到的行插入到我的数据库中 现在的问题是,如果我运行这段代码,它会在我的数据库中插入所有的txt文件,我不知道为什么Php 过滤出TXT中的行并插入数据库,php,mysql,mysqli,Php,Mysql,Mysqli,我试图在txt文件的一行中搜索字符串,包含我正在搜索的字符串的行必须插入到我的数据库中 php在遍历所有行时,正如我所说,我正在尝试将它找到的行插入到我的数据库中 现在的问题是,如果我运行这段代码,它会在我的数据库中插入所有的txt文件,我不知道为什么 $search = $_GET["search"]; $logfile = $_GET['logfile']; // Read from file $file = fopen($logfile, "r"); ?> <head&g
$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);
如果不清楚,请询问任何问题$array=file$filename读取数组中$filename中给定的文件,每行一个,然后可以使用foreach迭代数组并在每行中搜索。如果您的搜索字符串与该行匹配,请插入数据库
$lines = file($logfile);
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
foreach($lines as $line) {
if(stristr($line,$search))
$sql = "INSERT INTO `ingamebanlist` (Ban, Timestamp) VALUES ('$line', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
// ...
}
}
很可能是因为您没有构造代码。罪魁祸首是这样的支票:
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(...);
}
尝试用以下循环替换您的循环:
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);
}
$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();
echo "<font face='Arial'> $line </font><hr>";
}
}
}
fclose($file);
你能给我们提供你的文件内容和搜索字符串的样本吗?