-2

<?php
//Connection Variable to establish connection to the database parameters and localhost, user, password
$connection = mysql_connect("localhost","root","") or die(mysql_error());

//selects the database called trial and uses the connection details
mysql_select_db("bb",$connection);

//Checks to see if a file has been submitted 
if(isset($_POST['submit'])){

 // if submitted

/*Propriety Information if user needs to be added*/
/*

$gym=mysql_real_escape_string($_POST['Gym']);
$access=mysql_real_escape_string($_POST['accessID']); 
$Chal=mysql_real_escape_string($_POST['Chal']);     


*/

//Files path with the added extention of a random name at the end.
$file=$_FILES['file']['tmp_name'];
echo $file;
//Force Open the file in read state 
$handle = fopen($file, "r");

fgetcsv($handle,1000,",");
fgetcsv($handle,1000,",");
fgetcsv($handle,1000,",");

//initates a check for the csv
if(($filedata =fgetcsv($handle,1000,",")) !== false )
{

 //While loop with the ammount of data in the csv, fgetcsv grabs all the data that is open. Each cell is restricted to 1000 charachters, then seperated by a comma 

 while(($filedata =fgetcsv($handle,1000,",")) !== false )
 {
   //Cycles through the row and each cell is then put into an array

   // Multidimensional array tutorial  E- Excel,  DBS - Database
          
   $userIDP2 = $filedata[0];     // E 1. User ID , DBS - userid
   $height = $filedata[1];   // E 2. Height,    DBS - height
   $genderIdentifier = $filedata[2];   // E 3. gender,    DBS - gender (UserTable)
   $testDateChange = $filedata[4];  // E 5. Test Date / Time,  DBS - testDate 
   $weight = $filedata[5];  // E 6. Weight,  DBS -  weight
   $bodyFatMass = $filedata[23]; // E 24. BFM (Body Fat Mass),  DBS - bodyFatMass
   $SkeletalMuscle = $filedata[32]; // E 33. SMM (Skeletal Muscle Mass), DBS - SkeletalMuscle
   $bodyFatP = $filedata[38]; // E 39. BFP (Body Fat Percentage), DBS - bodyFatP
   $lean_RA = $filedata[62]; // E 63. LM of Right Arm,             DBS - lean_RA
   $lean_LA = $filedata[64]; // E 65. LM of Left Arm,              DBS - lean_LA
   $lean_Trun = $filedata[66]; // E 67. LM of Trunk (Abdomin),   DBS - Lean_Trun       
   $lean_RL = $filedata[68]; // E 69. LM of Right Leg,             DBS - lean_RL
   $lean_LL = $filedata[70]; // E 71. LM of Left Leg,             DBS - lean_LL
   $wc_TargetW = $filedata[73]; // E 74 Target Weight,             DBS - wc_TargetW
   $BMR = $filedata[77]; // E 78.BMR,                              DBS - BMR
   $visceralFat1 = $filedata[81]; // E 82.Visceral Fat Level,       DBS - visceralFat
   
   /*Replaces specific characters strings for the associated data */
   $userIDR2 = str_replace("<","",$userIDP2);
   $userID = str_replace(">","",$userIDR2);
   $visceralFat = str_replace("level","",$visceralFat1);

   $HyphenDate = str_replace('.','-' , $testDateChange);

   $date = DateTime::createFromFormat('d-m-Y H:i:s', $HyphenDate);
   echo  $date->format('Y-m-d h:i:s');
   echo $date;

   //Variable Declare
   $Gender ='';

   // To check if Male or Female
   if($genderIdentifier == 'M' || $genderIdentifier == 'm'){
    $Gender = "Male";
   }else if($genderIdentifier == 'F' || $gender == 'f'){
    $gender = "Female";
   }else{

    $gender = "intermittent";
   }

   //Change the Date Time format
   echo"<br/>";
   
   

  


   //sql query
   $sqlBodyCompositionStart="
   INSERT INTO  `bodycomp` 
   (
    `userid`,
    `height` ,
    `testDate` ,
    `weight`,
    `bodyFatMass`,
    `SkeletalMuscle`,
    `bodyfatP`,
    `lean_RA`,
    `lean_LA`,
    `lean_Trun`,
    `lean_RL`,
    `lean_LL`,
    `wc_TargetW`,
    `BMR`,
    `visceralFat`
   )VALUES (
    '".$userID."',
    '".$height."',
    '".$testDate."',
    '".$weight."',
    '".$bodyFatMass."',
    '".$SkeletalMuscle."',
    '".$bodyFatP."',
    '".$lean_RA."',
    '".$lean_LA."',
    '".$lean_Trun."',
    '".$lean_RL."',
    '".$lean_LL."',
    '".$wc_TargetW."',
    '".$BMR."',
    '".$visceralFat."'
   );";


   $sqlBodyCompositionEnd="
   INSERT INTO  `bodycomp` 
   (
    `height_1` ,
    `testDate_1` ,
    `weight_1`,
    `bodyFatMass_1`,
    `SkeletalMuscle_1`,
    `bodyfatP_1`,
    `lean_RA_1`,
    `lean_LA_1`,
    `lean_Trun_1`,
    `lean_RL_1`,
    `lean_LL_1`,
    `wc_TargetW_1`,
    `BMR_1`,
    `visceralFat_1`
   )VALUES (
    '".$height."',
    '".$testDate."',
    '".$weight."',
    '".$bodyFatMass."',
    '".$SkeletalMuscle."',
    '".$bodyFatP."',
    '".$lean_RA."',
    '".$lean_LA."',
    '".$lean_Trun."',
    '".$lean_RL."',
    '".$lean_LL."',
    '".$wc_TargetW."',
    '".$BMR."',
    '".$visceralFat."'
   );";
   
   
           // Check for user name
   $userNameSQL ="SELECT *
   FROM user 
   WHERE username ='".$userID."'";
   $userCheck = mysql_query($usernameSQL) or die(mysql_error());
     
   if(mysql_num_rows($userCheck)==1)  //If rows are return
   {
    $sqlBodyCompositionEnd;
    $uploadData = mysql_query($sqlBodyCompositionEnd) or die(mysql_error());
    if($uploadData)
    {
     echo"Data has uploaded";
    }
    else
    {
     echo "Data has not been uploaded";
    }
   } 
   else
   {
     // Adds a new User
       // SQL Query
       $sql =" INSERT INTO `user`(`UserName`,`gender`,) 
            VALUES
             ('".$userID."','".$gender."')";
             $userID = mysql_insert_id();
             $resultNA = mysql_query($sql) or die(mysql_error()); //run your SQL query
               

    if($resultNA)
    {
     echo"A new User has been added";
     // Once a new user has been added, it then tried to add data
     $sqlBodyComposition;
     $uploadData = mysql_query($sqlBodyCompositionStart) or die(mysql_error());
     if($uploadData)
     {
      echo"Data has uploaded";
     }
     else
     {
      echo "Data has not been uploaded";
     }
    }
    else
    {
     echo "There is no user";
    }
   } 
  }
 }
}

/*


OBJECTIVE FOR FILE: 

This file grabs the file that was posted and cycles the data in the csv; to avoid duplication of pages, the bottom half the code should check to see if an existing 
user is there; if it is, it uses the same code that would be used if the listed memeber wasn't in the database. This means that $sqlBodyComposition should be a
universal variable which will limit duplication. 

We need to create a function that checks for a user, returns true and inserts the
$sqlBodyComposition query. If a user doesn't exist, we need to remove "<" and ">" 
in the ID insert a new user. When the user is inserted, it is to then insert that
data about the body composition to the user. 

It is to return to a page and determine whether it succeeded or not. 

*/

?>

So I have a date in a csv file and I need php to convert it to a more appropriate format which is Y-m-d h:i:s

the format I need to convert 10.05.2017 18:31:07 this is stored as a variable/string

I've used str_replace('.','-',$date);

and I now need to reverse the Year and Date to achieve the submit-able format

is it possible to grab some help with this?

  • Look into `DateTime::createFromFormat()`. That will give you a `DateTime` object, which you can then `->format()` into the desired format. – rickdenhaan May 28 '17 at 11:57

2 Answers2

-1

It would probably be easier to create a date object rather than rearranging the string.

This code should work for what you want to do:

<?php
    //Raw Input as string
    $raw = "10.05.2017 18:31:07";
    //Create date object
    $date = DateTime::createFromFormat('d.m.Y H:i:s', $raw);
    //Print out date object
    echo $date->format('Y-m-d h:i:s');
?>

The documentation for createFromFormat can be found here: http://php.net/manual/en/datetime.createfromformat.php

Conor.

cwalsh
  • 39
  • 4
  • Yeah This is odd because I've tried that exact method, and it failed to rearrange the object; – user3701575 May 28 '17 at 12:15
  • Could you add add some of your code so that I could better help you? I have run the code on http://phpfiddle.org/ and it worked. – cwalsh May 28 '17 at 12:22
  • Outputs this error, Call to a member function format() on a non-object $HyphenDate = str_replace('.', '-' , $testDateChange); $date = DateTime::createFromFormat('d.m.Y H:i:s', $HyphenDate); echo $date->format('Y-m-d h:i:s'); echo $date; – user3701575 May 28 '17 at 12:23
  • added the code. – user3701575 May 28 '17 at 12:27
  • You still have the string replace (HyphenDate) there this changes the dots to hyphens but the date format that you have used is dots not hyphens. So if you change this: $HyphenDate = str_replace('.', '-' , $testDateChange); $date = DateTime::createFromFormat('d.m.Y H:i:s', $HyphenDate); echo $date->format('Y-m-d h:i:s'); echo $date; TO $HyphenDate = str_replace('.', '-' , $testDateChange); $date = DateTime::createFromFormat('d.m.Y H:i:s', $testDateChange); echo $date->format('Y-m-d h:i:s'); That should fix the problem – cwalsh May 28 '17 at 12:36
  • Yeah I just noticed that, and then I also realised that I wasn't using the DateTime Object correctly; Thanks for your help though man. Very much appreciated! :) – user3701575 May 28 '17 at 12:43
  • No bother happy to help :-) – cwalsh May 28 '17 at 12:45
-1

Solved this by removing the decimal but also spotted a misuse of the object.