-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.php
More file actions
95 lines (76 loc) · 2.67 KB
/
init.php
File metadata and controls
95 lines (76 loc) · 2.67 KB
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
<?php
// Parse command-line arguments
$options = getopt("h:u:p:d:");
$host = $options['h'] ?? null;
$user = $options['u'] ?? null;
$password = $options['p'] ?? null;
$dbName = $options['d'] ?? null;
// Validate the required parameters
if (!$host || !$user || !$dbName) {
showError("Database host (-h), user (-u), and name (-d) are required. Password (-p) is optional.");
}
// Main script logic
$mysqli = new mysqli($host, $user, $password);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Create the configuration file
createConfigFile($host, $user, $password, $dbName);
// Create the database if it doesn't exist
createDatabase($mysqli, $dbName);
// Switch to the newly created database
$mysqli->select_db($dbName);
// Execute all SQL files from the db/create folder
executeSqlFiles($mysqli, 'db/create');
// Close the connection
$mysqli->close();
echo "Database init complete.\n";
// Function to create the config file
function createConfigFile($host, $user, $password, $dbName) {
$configContent = "<?php\n";
$configContent .= "define('DB_HOST', '$host');\n";
$configContent .= "define('DB_USER', '$user');\n";
$configContent .= "define('DB_PASSWORD', '$password');\n";
$configContent .= "define('DB_NAME', '$dbName');\n";
$configContent .= "?>\n";
file_put_contents("config.php", $configContent);
echo "Configuration file created: config.php\n";
}
// Function to check if the database exists
function databaseExists($conn, $dbName) {
$result = $conn->query("SHOW DATABASES LIKE '$dbName'");
return $result->num_rows > 0;
}
// Function to create the database if it doesn't exist
function createDatabase($conn, $dbName) {
if (!databaseExists($conn, $dbName)) {
echo "Database does not exist. Creating database: $dbName...\n";
$conn->query("CREATE DATABASE $dbName");
echo "Database created successfully.\n";
} else {
showError("Database $dbName already exists");
}
}
// Function to execute all SQL files from the specified folder
function executeSqlFiles($conn) {
$sqlFiles = glob('db/create/' . '*.sql');
foreach ($sqlFiles as $file) {
echo "Executing SQL file: $file\n";
$sql = file_get_contents($file);
if ($conn->multi_query($sql)) {
do {
// Processing results of each query
} while ($conn->next_result());
echo "Executed SQL file: $file\n";
} else {
showError("Error executing SQL file $file: " . $conn->error);
}
}
}
// Function to display an error and exit
function showError($message) {
echo "Error: $message\n";
exit(1);
}
?>