我正在尝试在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);
如果不清楚,请询问任何问题
答案 0 :(得分:0)
$array = file($filename)
读取数组中$filename
中给出的文件(每行一个),然后您可以使用ie 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 {
// ...
}
}
答案 1 :(得分:0)
这很可能是因为您没有构建代码。罪魁祸首是这样的检查:
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(...);
}
答案 2 :(得分:0)
尝试用这个替换你的循环:
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);