简体   繁体   English

如何通过上传 CSV 文件来使用 php 更新数据库?

[英]How to update a database using php by uploading a CSV file?

I have some code here to update my database based on two columns in the CSV.我这里有一些代码可以根据 CSV 中的两列更新我的数据库。 The CSV file would look like this: CSV 文件如下所示:

ID Response身份响应

1 Hello1 1 你好1

2 Hello2 2 你好2

3 Hello3 3 你好3

In my database I have a table that also contains an id column and an extra column that matches response.在我的数据库中,我有一个表,其中还包含一个 id 列和一个与响应匹配的额外列。 The idea is this CSV file is uploaded and will populate the response that matches the ID number.这个想法是这个 CSV 文件已上传,并将填充与 ID 号匹配的响应。

Basically this: " UPDATE tbl_data SET response = {$response} WHERE id = {$id} "基本上是这样的:“ UPDATE tbl_data SET response = {$response} WHERE id = {$id}

The form that performs this action look like this:执行此操作的表单如下所示:

<form method="post" name="uploadCSV" enctype="multipart/form-data">
    <label>Choose CSV File</label>
    <input type="file" name="csv_file" id="file" accept=".csv" />
    <button type="submit" name="import" class="read-more smaller">Upload</button>
</form>

However, I don't think I've understood how to do this properly, as I get SQL errors, or the form just sits there as if nothing has happened.但是,我不认为我已经理解如何正确执行此操作,因为我收到 SQL 错误,或者表格只是坐在那里,好像什么都没发生一样。 See code below.请参阅下面的代码。

if (isset($_POST["import"])) {

    if($_FILES["csv_file"]["name"]){

        $filename = explode(".", $_FILES["csv_file"]["name"]);

        if(end($filename) == "csv"){

            $handle = fopen($_FILES["csv_file"]["tmp_name"], "r");

            while ($data = fgetcsv($handle)){

                $id = $data[0];
                $response = $data[1];

                $query ="UPDATE tbl_data SET response = {$response} WHERE id = {$id}";
                $update_data = mysqli_query($connection,$query);

                if (!$update_data) {
                    $message = "There was a problem updating your CSV file. If this problem reoccurs, please contact admin";
                    die (mysqli_error($connection));
                }

            }

            fclose($handle);

            header("Location: upload.php?uploaded=1");

        } else {
            $message = "You can only upload a CSV file.";
        }

    } else {
        $message = "Please select a CSV file.";
    }

}

I have the $message to shows the message.我有 $message 来显示消息。 but it doesn't show up any of the messages, and the update in the database doesn't appear to take place either.但它没有显示任何消息,并且数据库中的更新似乎也没有发生。

Is there any errors that I may have overlooked in my code?我的代码中是否有任何我可能忽略的错误? Or is there a much better way to do this?还是有更好的方法来做到这一点?

Got it working by using the following通过使用以下方法使其工作

if(isset($_POST["importcsv"])){

        $file = $_FILES["csv_file"]["tmp_name"];
        $handle = fopen($file,"r");

        while ($row = fgetcsv($handle)) {

            $id = $row[0];
            $response = $row[1];

            $sql = "UPDATE table SET response = ? WHERE id = ?";
            $update_data_stmt = mysqli_stmt_init($connection);

            if (!mysqli_stmt_prepare($update_data_stmt, $sql)){
                die("Something went wrong with the upload. " . mysqli_error($connection));
            } else {
                mysqli_stmt_bind_param($update_data_stmt, "ss", $response, $id);
                mysqli_stmt_execute($update_data_stmt);
                if ($id == "ID" && $response == "Response"){
                    echo "";
                } else {
                    echo "Lead <b>{$id}</b>'s response was updated to <b>{$response}</b>.</p>";
                }
            }

        }

    }

I suspect something goes wrong with your database, since you say your $message is echoed after all of this but is empty.我怀疑你的数据库出了问题,因为你说你的$message在这一切之后被回显但是是空的。 Assuming that your $data contain the correct information (I would suggest var_dump() ing to make sure), I could only imagine the statement not executing as should.假设您的$data包含正确的信息(我建议var_dump()确保),我只能想象该语句没有按应有的方式执行。

I'm not too well versed in mysqli , however you might want to consider using PDO to see if it works.我不太精通mysqli ,但是您可能需要考虑使用PDO来查看它是否有效。 It also protects you against potential SQL Injection attacks from the csv file:它还可以保护您免受来自 csv 文件的潜在 SQL 注入攻击:

$conn = new PDO(db_host, db_user, db_pw)
while ($data = fgetcsv($handle)) {
    $id = $data[0];
    $response = $data[1];

    $sql = "UPDATE tbl_data SET response = :response WHERE id = :id";
    $st = $conn->prepare($sql)
    $st->bindValue(":response", $response, PDO::PARAM_STR)
    $st->bindValue(":id", $id, PDO::PARAM_INT)
    $st->execute();
    //Output
    print_r($st->errorInfo());
}
$conn = null;

Try this and errorInfo() should give you sufficient logs to see what is wrong.试试这个, errorInfo()应该会给你足够的日志来看看有什么问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM