-3

I have this lines of code in php which reads a file in CSV format with a structure of a mySQL database and display the SQL code needed to create it. The only issue i'm getting here is that i can't print out the primary key variable because it says it's not defined, even though i defined it earlier. Can someone help me explaining why am i getting this error? Here is my code:

    <?php
      $line = 1;
      echo "CREATE TABLE IF NOT EXISTS clientes( <br>";
    
      if (($file = fopen("DB.csv", "r")) !== FALSE) {
          while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
              $str = explode(";", $data[0]);

              if($line != 1) {
                  echo "". $str[0]. " ". $str[1];
              if($str[2] == "NO") {
                  echo " NOT ";
              } else {
                  echo " DEFAULT ";
              }

              echo " ".$str[4]." ".$str[5].",<br>";
    
              if($str[3] == "PRI") {
                  $primarykey = $str[0];
              }
          }
          $line++;
      }

      echo "PRIMARY KEY (" .$primarykey. ") <br>";
      echo ") ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
      fclose($file);
}
?>
ADyson
  • 57,178
  • 14
  • 51
  • 63
neptune17
  • 19
  • 6
  • If not, please share more details, like the error message you are facing and your attempts to resolve it – Nico Haase Dec 10 '21 at 11:50
  • 1
    Presumably you code never entered the `if($str[3] == "PRI")` block, and therefore the variable was never defined. What debugging have you done? We can't see the content of the CSV so we can't predict what will happen. – ADyson Dec 10 '21 at 11:51

1 Answers1

1

My code never entered the if($str[3] == "PRI)" so I checked before and i noticed it wasn't looping through the first if statement inside in while loop. I had to change the if statement from $line != 1 to $line > 0 so that it would check the first line that contained the primary key. After that, my variable was already defined which answers my question. Thanks to ADyson for helping me find the error.

neptune17
  • 19
  • 6