1

Following code which is used to browse csv file. Fatch data from csv and store in a MySQL database.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</head>

<body>
    <form name="import" method="post" enctype="multipart/form-data">
        કેમ છે: <input type="file" name="file" /><br />
        <input type="submit" name="submit" value="Submit" />
    </form>
<?php
    include ("connection.php");

    if(isset($_POST["submit"]))
    {
        $file = $_FILES['file']['name'];
        $handle = fopen($file, "r");
        $c = 0;
        while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
        {
            $name = $filesop[0];
            $marks = $filesop[1];
            mysql_query("set name utf8");
            $query = "INSERT INTO temp (name, marks) VALUES ('".$name."','".$marks."')";
            echo $query;
            $sql = mysql_query($query);
        }
    }
?>

    </div>
</body>
</html>

Following code is used connect database.

<?php

    $hostname = "localhost";
    $username = "root";
    $password = "";
    $database = "test";
    $conn = mysql_connect("$hostname","$username","$password") or die(mysql_error());
    mysql_select_db("$database", $conn) or die(mysql_error());

?>

When I run code its stored data like "????????".

My CSV file like below

enter image description here

Following phpmyadmin version information

enter image description here

Following is my table structure

enter image description here

Hardik Visa
  • 323
  • 6
  • 23

1 Answers1

1

if you're getting stored ???????? in database, then,

You need to check the database collation first, change it to utf8_general_ci or utf8mb4_general_ci if simple utf_general_ci doesn't work.

Second, if collation is fine then it could also be possible that string is already in utf8 format, and you're converting it forcefully again.

Use following function to convert string to utf8.

function convToUtf8($str){ 
    if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")!="UTF-8" ) 
        return  iconv("gbk","utf-8",$str);
    else
        return $str; 
}

Then in your code

while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
    $name = convToUtf8($filesop[0]);
    $marks = convToUtf8($filesop[1]);
    //mysql_query("set name utf8");   No need to do this now
    $query = "INSERT INTO temp (name, marks) VALUES ('$name','$marks')";
    echo $query;
    $sql = mysql_query($query);
}

and look here and set db collation enter image description here

Mubin
  • 4,325
  • 5
  • 33
  • 55