Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to mysql date format before insert [duplicate]


I have a form which is used to upload a .csv file to insert data in mysql table. The file has a date column in a format "dd/mm/yyy". However I want to insert this date string in mysql date format "yyyy-mm-dd". I have the following code so far.

//parse data from csv file line by line
        while(($line = fgetcsv($csvFile)) !== FALSE){
         //insert member data into database
         $db->query("INSERT INTO txns (txn_date, description, amount, status) VALUES ('".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[3]."')");
            }
        }

        //close opened csv file
        fclose($csvFile);

Please help to convert the date string to mysql date (yyyy-mm-dd) format.

like image 529
sohal07 Avatar asked Sep 23 '26 12:09

sohal07


2 Answers

You can do it like this:

$var = '05/01/2017';
$date = str_replace('/', '-', $var);
$result = date('Y-m-d', strtotime($date));

Output: 2017-01-05.

Try this:

$date = date('Y-m-d', strtotime($line[0]));  
// convert date to yyyy-mm-dd

and use $date as the value of column txn_date

like image 32
Mayank Pandeyz Avatar answered Sep 26 '26 02:09

Mayank Pandeyz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!