1+ <?php
2+ if (PHP_SAPI !== 'cli ' || isset ($ _SERVER ['HTTP_USER_AGENT ' ])):
3+ die ('Please run only from cli ' );
4+ endif ;
5+
6+ /**
7+ * Include Dotenv library to pull config options from .env file.
8+ */
9+ if (file_exists (__DIR__ . '/vendor/autoload.php ' )) {
10+ require_once __DIR__ . '/vendor/autoload.php ' ;
11+
12+ $ dotenv = Dotenv \Dotenv::create (__DIR__ , '/env/.env ' );
13+ $ dotenv ->load ();
14+
15+ } else {
16+ die ('Please install via composer and setup a new .env file! ' );
17+ }
18+
19+ try {
20+ $ conn = new mysqli (getenv ('DB_HOST ' ), getenv ('DB_USERNAME ' ), getenv ('DB_PASSWORD ' ), getenv ('DB_DATABASE ' ));
21+ mysqli_set_charset ($ conn ,"utf8 " );
22+
23+ if ($ conn ->connect_error ) {
24+ die ("Connection failed: " . $ conn ->connect_error );
25+ }
26+
27+ $ db = getenv ('DB_DATABASE ' );
28+ echo "Connected DB: $ db \n\n" ;
29+
30+ $ csv = 'zip.csv ' ;
31+
32+ function csvToArray ($ filename ='' , $ delimiter =', ' )
33+ {
34+ if (!file_exists ($ filename ) || !is_readable ($ filename ))
35+ return FALSE ;
36+ $ header = NULL ;
37+ $ data = array ();
38+ if (($ handle = fopen ($ filename , 'r ' )) !== FALSE )
39+ {
40+ while (($ row = fgetcsv ($ handle , 1000 , $ delimiter )) !== FALSE )
41+ {
42+ if (!$ header )
43+ $ header = $ row ;
44+ else
45+ $ data [] = array_combine ($ header , $ row );
46+ }
47+ fclose ($ handle );
48+ }
49+ return $ data ;
50+ }
51+
52+ $ data = csvToArray ($ csv );
53+ foreach ($ data as $ d ) {
54+ $ zip = $ d ['zip ' ];
55+ $ city = $ d ['city ' ];
56+ $ district = $ d ['district ' ];
57+
58+ $ sql = "INSERT INTO zip(zip, city, district)
59+ VALUES (' $ zip', ' $ city', ' $ district') " ;
60+
61+ if ($ conn ->query ($ sql ) === TRUE ) {
62+ echo "Zip inserted: $ zip --------–> \n" ;
63+ } else {
64+ echo "Unable to save, try again --------–> \n" ;
65+ }
66+ }
67+
68+ $ conn ->close ();
69+
70+ } catch (Exception $ e ) {
71+ echo 'Script error: ' . $ e ->getMessage ();
72+ exit (1 );
73+ }
0 commit comments