我写了一个脚本来下载Google工作表,然后将此工作表上传到我的dadabase。

除了现在将数据上传到我的数据库之外,其他所有东西似乎都运行良好。

我导航到该文件夹​​,然后运行以下命令:

php -f updatedatabase.php


这是我编写的脚本(用实际的密钥填充了googel工作表密钥-我测试了链接,并且该链接可以正常工作,并且出于安全原因,数据库凭据已加注星标):

<?php
    $datas = file_get_contents("https://docs.google.com/spreadsheets/d/1fOe2fz8PmYzTWU7l_KboHdv0zP0KZkhcJUTGJDUXaKk/gviz/tq?tqx=out:csv&sheet=All%20Items&range=A:G");
    $datas = explode( PHP_EOL, $datas );
    //FORMAT ("Name1", "Image1", "Description1", "Rarity1", "Price1", "Status1", "Store1"), ("Name2", "Image2", "Description2", "Rarity2", "Price2", "Status2", "Store2").....

    // Info to connect to the database
        $servername = ".com";
        $dbusername = "";
        $password = "!19";
        $dbname = "";

        $con=mysqli_connect( $servername, $dbusername, $password, $dbname );

    mysqli_query( $con, "TRUNCATE TABLE Items" );

    foreach ( $datas as $data ) {
        echo $data . "\n";
        mysqli_query( $con, "INSERT INTO Items (Name,Image,Description,Rarity,Price,Status,Store) VALUES " . $data );
    }

    mysqli_close($con);
?>

最佳答案

您的data字符串格式不正确:

$csvData = file_get_contents("https://docs.google.com/spreadsheets/d/1fOe2fz8PmYzTWU7l_KboHdv0zP0KZkhcJUTGJDUXaKk/gviz/tq?tqx=out:csv&sheet=All%20Items&range=A:G");
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}

// format the data string
// work with PHP7.0 or later
$datas = array_map(function ($data) {
    $dataString = implode("','", $data);
    return "('$dataString')";
}, $array);

// remove the head line
array_shift($datas);

// Info to connect to the database
$servername = "192.168.10.10";
$dbusername = "homestead";
$password = "secret";
$dbname = "gooledoc";

$con = mysqli_connect($servername, $dbusername, $password, $dbname);

mysqli_query($con, "TRUNCATE TABLE Items");

foreach ($datas as $data) {
    echo $data . "\n";
    $result = mysqli_query($con, "INSERT INTO `Items` (`Name`,`Image`,`Description`,`Rarity`,`Price`,`Status`,`Store`) VALUES " . $data);
    var_dump($result);
}

mysqli_close($con);

关于php - PHP CSV上传到MySQL无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51914365/

10-12 06:58