1

我正在开发一个脚本,它以 csv 作为输入,然后读取文件并将其内容插入 mysql 数据库。所以问题是在将数据插入数据库时​​出现的。它将 UMLAUT 转换为随机字符。

仅供参考——我的数据库在 latin_german_ci 中。[我也尝试将其更改为 UTF8]

我能够在 Web 浏览器中显示 UMLAUT 字符,但是当我尝试通过 sql 查询将它们插入数据库时​​,它会插入随机字符。

<?php

function uploadCsv($filename){

    echo "filename - ".$filename."<br/>";

    if(isset($filename) || $filename == ""){ // return with an error msg.

    }else{
        $pos = stripos($filename, ".csv");
        if($pos == 0 || $pos != strlen($filename)-4){
            //echo "invalid format";
            return ;
        }
    }

    set_time_limit(0);
    $error = "";
    $row = 0;
    $handle = fopen($filename, "r");
    //echo "<br/>".$filename."<br/>";
    //echo "<br/>".$handle."<br/>";
    if($handle == null){

        return "unable to process";
    }

    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {

        if ($row == 0) {
            // this is the first line of the csv file
            // it usually contains titles of columns
            // do nothing.
            $num = count($data);
            //echo "num - ".$num."<br/>";
            if($num != 2){
                // echo "returning back";
                return "invalid CSV format.";
            }
        }
        // this handles the rest of the lines of the csv file
        $num = count($data);
        $id = $data[0];
        $inserQuery = "";
        $inserQuery =  "INSERT INTO `table` (
                            `ID` ,
                            `Productname`
                            )
                            VALUES (";

        for ($c=0; $c < $num; $c++) {
            if($c==0){
                $inserQuery .= " '". utf8_encode($data[$c])."'" ;
            }else{
                $inserQuery .= ", '". utf8_encode($data[$c]) ."'" ;
            }
        }
        $inserQuery .= ");";
        echo $inserQuery."<br/>";
        mysql_query($inserQuery);
        if(mysql_affected_rows() == -1 || mysql_affected_rows() <1){
            echo "error<br/>";
        }else{
            echo "row inserted - ".$row." with ID = ".$id." <br/>";
        }
        $row++;
    }
    fclose($handle);
    return "1";
}
?>

请帮忙....

谢谢

4

2 回答 2

2

相同的程序...请参阅

是否使用“SET NAMES”

是否需要“SET CHARACTER SET utf8”?

本质上,您必须告诉 MySQL 它应该从客户端(您的 PHP 脚本)获得哪个字符集。

于 2010-05-20T13:29:41.427 回答
0

为什么将 utf8_encode() 用于拉丁数据库?您的网页编码是什么(HTTP Content-Type 和 HTML 元标记)?源代码的编码是什么(您可以在编辑器中配置它)?您使用哪个程序查看数据库以及使用哪种编码?

于 2010-05-20T13:29:57.180 回答