Search code examples
phpmysqlcsvfgetcsv

fgetcsv insert values order by $fileop


I have a CSV file with 3 columns lastname, firstname, matricule and I would like to import them with order by matricule

Currently I have this working PHP code:

$query = "TRUNCATE TABLE `personnal` ";
        $result = mysql_query($query);
        $file = $_FILES['file']['tmp_name'];
        $handle = fopen($file, "r");
        while (($fileop = fgetcsv($handle, 1000, ";")) !== false) {

            $lastname = $fileop[0];
            $firstname = $fileop[1];
            $matricule = $fileop[2];
            $sql = mysql_query("INSERT INTO personnal (lastname,firstname,matricule,usermaj) VALUES ('$lastname','$firstname','$matricule','importCSV')");
        }

I tried to add ORDER BY $matricule but it was too easy to work.

$sql = mysql_query("INSERT INTO personnal (lastname,firstname,matricule,usermaj) VALUES ('$lastname','$firstname','$matricule','importCSV') ORDER BY '$matricule'");

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY' at line 1(errno)

We will import every week this kind of CSV file and I need to have the auto AI id to be the same all the time. Mister X cannot be one week id=61 and next week id=63. If ORDER BY '$matricule' during the importation is possible it should solve my problem. Otherwise I have to do it manualy while converting it to CSV.


Solution

  • I've finaly come up to the idea an unique ID like MD5 is the best. I also need history so I removed TRUNCATE table

    Solution :

    $personnal_id = md5($lastname.$fistname);
    
                $resultpersonnal_id = mysql_query("SELECT COUNT(*) AS number FROM personnal WHERE personnal_id='$personnal_id'");
                $number=mysql_result($resultpersonnal_id, 0, 'number');
    
    
    
                if ($number == 0) {
                    $sql = mysql_query("INSERT INTO personnal (personnal_id,lastname,firstname,matricule,usermaj) VALUES ('$personnal_id','$lastname','$firstname','$matricule','importCSV')");
    
                }