-
Notifications
You must be signed in to change notification settings - Fork 21
/
Import.php
122 lines (104 loc) · 3.16 KB
/
Import.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?php
namespace Thamaraiselvam\MysqlImport;
use mysqli;
use Exception;
/**
* Mysqli class to import sql from a .sql file
*/
class Import
{
private $db;
private $filename;
private $username;
private $password;
private $database;
private $host;
private $port;
/**
* instanciate
* @param $filename string name of the file to import
* @param $username string database username
* @param $password string database password
* @param $database string database name
* @param $host string address host localhost or ip address
* @param $port int port for the host, default is 3306
*/
public function __construct($filename, $username, $password, $database, $host, $port = 3306)
{
//set the varibles to properties
$this->filename = $filename;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->host = $host;
$this->port = $port;
//connect to the datase
$this->connect();
//open file and import the sql
$this->openfile();
}
/**
* Connect to the database
*/
protected function connect()
{
$this->db = $this->createconnection();
if ($this->db->connect_errno) {
throw new Exception("Failed to connect to MySQL: " . $this->db->connect_error);
}
}
/**
* run queries
* @param string $query the query to perform
*/
protected function query($query)
{
if (!$this->db->query($query)) {
throw new Exception("Error with query: ".$this->db->error."\n");
}
}
/**
* Open $filename, loop through and import the commands
*/
protected function openfile()
{
try {
//if file cannot be found throw errror
if (!file_exists($this->filename)) {
throw new Exception("Error: File not found.\n");
}
// Read in entire file
$fp = fopen($this->filename, 'r');
// Temporary variable, used to store current query
$templine = '';
// Loop through each line
while (($line = fgets($fp)) !== false) {
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '') {
continue;
}
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';') {
$this->query($templine);
// Reset temp variable to empty
$templine = '';
}
}
//close the file
fclose($fp);
} catch (Exception $e) {
echo "Error importing: ".$e->getMessage()."\n";
} finally {
$this->db->close();
}
}
/**
* @codeCoverageIgnore
*/
protected function createconnection()
{
return new mysqli($this->host, $this->username, $this->password, $this->database, $this->port);
}
}