尝试以CSV文件中的特定行为目标[已关闭]

ggazkfy8  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(88)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

12天前关闭。
Improve this question
我每天都有一个基本结构相同的CSV文件。我每周都会将其中的一部分放入我的数据库。可以说,我用特定的条件搜索找到了大部分数据。
这些确实抓取了我需要的信息,但是我遇到了一个特殊的例子,在这个例子中,这并不能抓取我想要的信息,因为数据在与标题分开的一行和一列上。
下面是一个例子:

$file = fopen($fname, "r");
while(! feof($file)) {
    $data = fgetcsv($file);
    if (strtotime($data[0]) == true && (!empty($data[12]))) {
        $sql = "UPDATE numbers
                    SET tot='" . $data[13] . "'
                WHERE date = '" . $lastDay . "'";
           if ($conn->query($sql) === TRUE) {
            echo "<li><p>" . $conn -> affected_rows . " newly created record in <u>tot</u>.</p></li>";
        }
    }
}
kadbb459

kadbb4591#

很简单,从CSV中读取下一行,如果这一行包含您感兴趣的数据。正确使用MYSQLI_并准备和绑定查询并不难。

$file = fopen($fname,"r");

// prepare the query ONCE, it can then be run multiple times with an execute
// and new values applied to the ? each time with the bind_param()
$sql = "UPDATE numbers SET tot = ? WHERE date = ?";
$stmt = $conn->prepare($sql);

while(! feof($file)) {
    $data = fgetcsv($file);
    if (strtotime($data[0]) == true && (!empty($data[12]))) {
        // read next line, as dont want the one we tested        
        $data = fgetcsv($file);

        $stmt->bind_param('ss', $data[13], $lastday);
        // execute of an UPDATE returns true if it worked and false if it failed
        $res = $stmt->execute();
        if ($res) {
            // NOTE: UPDATE does not create a new row, it amends an existing one
            //echo "<li><p>" . $conn -> affected_rows . " newly created record in <u>tot</u>.</p></li>";
            echo "<li><p>" . $conn->affected_rows . " rows updated <u>tot</u>.</p></li>
        }
    }
}

相关问题