-2

I searched everywhere in the internet but I couldn't find a perfect solution for my question, regarding on how to validate the CSV Contents before it uploads and save it to database, I am using msqli for the database and PHP for the language script. For example I have 3 columns in localhost database:

These are my following headers I made both in locahost database and in CSV File (1.)Date (2.)Email (3.)Phone Number.

Before uploading and saving to the localhost database it should meet the restrictions of the contents are the ff: For the Date: It should mm/dd/yy ----> 1/31/2018 or 12/31/2018 For the Email: It should name@domain.com ----> saffron@gmail.com For the Number: It should 12 digits number only and the format is ----> 0906-021-0156

If those restrictions meets perfectly the CSV File will be uploaded and save to the database, if not it will throw an error or pop-up message.

I really don't know how to start the execution of program. I am really new to PHP so please help me with this.

This is the code I worked, and I am stack here...

<?php

$dbHost = 'localhost';
$dbUsername = '';
$dbPassword = 'root';
$dbName = 'dbUpload';

$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if ($db->connect_error) {
    die("Unable to connect database: " . $db->connect_error);
}

if(isset($_POST['submit'])){
 
 $row = 1;
 $mycsvfile = array(); //define the main array.
 
 if ($_FILES['csv']['size'] > 0) {
     //get the csv file 
      $file = $_FILES['csv']['tmp_name']; 
      $handle = fopen($file, "r");
      $i = 0;
      
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

        $num = count($data); 
         $row++;
 
      $mycsvfile[] = $data; //add the row to the main array.
      
      $headerDate = $mycsvfile[0][0];
      $headerEmail = $mycsvfile[0][1];
      $headerPhone =  $mycsvfile[0][2];

      if ($headerDate !== 'Date' || $headerEmail !== 'Email' || $headerPhone !== 'Phone Number') {
        $qstring = '?status=invalid_header';        
        fclose($handle);     
       }
       
       else {
        if ($i > 0) {
           
              $import = "INSERT into upload (techDate, techEmail, techPhone)values('$data[0]','$data[1]','$data[2]')";
              
              $db->query($import);
              $qstring = '?status=succ';
          }
       }
      $i++;        
  } 
  fclose($handle);
  
  

}
else{
 $qstring = '?status=err';
   }
}
header("Location: uploadvalid.php".$qstring);
?>
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Saffron
  • 1
  • 1
  • 6
  • This is a help forum and not a coding service. Surely you can find some code to read a CSV file and insert into a database, the next improvement is validating the data. – Nigel Ren Mar 27 '18 at 10:07
  • @NigelRen I am already done in coding for reading a CSV file and insert into the database, now I am working on validating the CSV contents file before inserting it to the database, to avoid errors on uploading because not all the time we are sure that the CSV file contains correct content. – Saffron Mar 27 '18 at 10:23
  • Add that code to the question as it shows you've made some effort. – Nigel Ren Mar 27 '18 at 10:24
  • @NigelRen please take a look for my code above, I hope you may help me – Saffron Mar 27 '18 at 10:36
  • So, you got your column data there, `$data[0]` etc. - now what is the exact problem you are facing in validating the content of those to your requirements …? – CBroe Mar 27 '18 at 10:38
  • _“the restrictions of the contents are the”_ - for each of those three, you are probably not the first one who ever had to do that kind of validation - so, what has your research turned up so far, how each of these restrictions could be implemented …? – CBroe Mar 27 '18 at 10:39
  • @CBroe, the problem is I don't know how to execute a program to validate those data or content from the CSV contains correct data then it will upload and save to the database. – Saffron Mar 27 '18 at 10:46
  • You don’t need to _“execute a program”_ ... You already managed to check whether the first row contains the right header names - did you “execute a program” for that …? No you didn’t, you wrote an appropriate if condition to perform the necessary checks. So now you do the same for these restrictions - and only perform the insert operation if those conditions where met to begin with. `if( (...) && (...) && (...) ) { /* perform insert */ }`Again: Your job now, to come up with the right `(...)` - we can help you with that if necessary, but you need to show us at least a reasonable attempt first. – CBroe Mar 27 '18 at 10:51
  • @CBroe Im perfectly done with header names. I am working now to the contents on how to validate or check those contents. – Saffron Mar 27 '18 at 10:54
  • _“Im perfectly done with header names”_ - I am not saying you weren’t ... *sigh* ... I am saying, at _that_ point you seemed to know how to perform some kind of validation of the data, by using an if statement. So what is keeping you from applying that same principle _again_ now, where does the _“I don't know how to execute a program to [...]”_ come from all of a sudden? When you had to validate those header names, you did not go “don’t know how to execute program” either, so what makes you think anything was any different now when it comes to validation of those other data fields …? – CBroe Mar 27 '18 at 11:00

1 Answers1

0

You can use the function preg_match().

I took the regex (for date and email) from StackOverflow. Links are below this code. I made the regex for your phone format.


<?php

$dbHost = 'localhost';
$dbUsername = '';
$dbPassword = 'root';
$dbName = 'dbUpload';

$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

if ($db->connect_error) {
    die("Unable to connect database: " . $db->connect_error);
}

if(isset($_POST['submit'])){

    $row = 1;
    $mycsvfile = array(); //define the main array.

    if ($_FILES['csv']['size'] > 0) {
        //get the csv file 
            $file = $_FILES['csv']['tmp_name']; 
            $handle = fopen($file, "r");
            $i = 0;


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

            $num = count($data);    
            $row++;

            $mycsvfile[] = $data; //add the row to the main array.

            $headerDate = $mycsvfile[0][0];
            $headerEmail = $mycsvfile[0][1];
            $headerPhone =  $mycsvfile[0][2];

            if ($headerDate !== 'Date' || $headerEmail !== 'Email' || $headerPhone !== 'Phone Number') {
                    $qstring = '?status=invalid_header';                    
                    fclose($handle);                
                }

                else {
                    if ($i > 0) {

                        $patternDate = '^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$';

                        $patternEmail = '(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])';

                        $patternPhone = '0906\d021\d0156';

                        // Check if the row has the correct format
                        if (preg_match($data[0], $patternDate)
                            && preg_match($data[1], $patternEmail)
                            && preg_match($data[2], $patternPhone)) {

                            // Format is OK, let's insert

                            $import = "INSERT into upload (techDate, techEmail, techPhone)values('$data[0]','$data[1]','$data[2]')";

                            $db->query($import);
                            $qstring = '?status=succ';

                         } else {
                             // The row doesn't have the right format
                             echo "The row $row doesn't have the right format";
                         }
                     }
                }
            $i++;                   
        }   
        fclose($handle);



}
else{
    $qstring = '?status=err';
    }
}
header("Location: uploadvalid.php".$qstring);
?>

link to the StackOverflow date regex

link to the StackOverflow email regex

txemsukr
  • 1,017
  • 1
  • 10
  • 32