· 9 years ago · Aug 07, 2017, 01:54 PM
1<?php
2$servername = "localhost";
3$username = "root";
4$password = "xxxxxx";
5//$currentDB;
6$conn;
7
8handleInMsg(); //this guy will call our constructive functions to make stuff happen
9
10
11
12function ConnectMySQL($currentDB) { //Connects to DB
13 $success = false;
14 // Create connection
15 if ($currentDB==null) {
16 $conn = new mysqli($servername, $username, $password);
17 }
18 if ($currentDB!=null) {
19 $conn = new mysqli($servername, $username, $password, $currentDB);
20 }
21 // Check connection
22 if ($conn->connect_error) {
23 //die("");
24 $success = false;
25 return $success;
26 }
27 $success = true;
28 return $success;
29}
30
31function disconMySQL() {
32 $conn->close();
33}
34
35function createDB($dbName) { //creates DB
36 $success = false;
37 $sql = "CREATE DATABASE IF NOT EXISTS ".$dbName;
38 if ($conn->query($sql) === TRUE) {
39 if (createTable()) {
40 $success = true;
41 return $success;
42 } else {
43 $success = false;
44 return $success;
45 }
46 } else {
47 $success = false;
48 return $success;
49 }
50
51}
52
53function createTable() { //automatically sets up tables for DB
54 $success = false;
55 $sql = "CREATE TABLE BoxSet (
56 id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
57 gap INT(6) UNSIGNED NOT NULL,
58 length INT(6) UNSIGNED NOT NULL,
59 currentTime TIMESTAMP
60 )";
61
62 if ($conn->query($sql) === TRUE) {
63 $success = true;
64 return $success;
65 } else {
66 $success = false;
67 return $success;
68 }
69}
70
71function insertData($gap, $length) {
72 $sql = "INSERT INTO BoxSet (gap, length)
73 VALUES ('".$gap."', '".$length."')";
74
75 if ($conn->query($sql) === TRUE) {
76 echo "New record created successfully";
77 } else {
78 echo "Error: " . $sql . "<br>" . $conn->error;
79 }
80}
81
82
83function handleInMsg() { //listens for commands via post
84 $command = $_POST["command"];
85 if ($command == "insertData") {
86 $postGap = $_POST["gap"];
87 $postLength = $_POST["length"];
88 insertData($postGap,$postLength);
89 return;
90 }
91 if ($command == "connectNewDB") {
92 $postNewDBName = $_POST["gap"];
93 ConnectMySQL();
94 createDB($postNewDBName);
95 return;
96 }
97 if ($command == "connectEDB") {
98 $postExistingDBName = $_POST["gap"];
99 ConnectMySQL($postExistingDBName);
100 return;
101 }
102 if ($command == "ping") {
103 echo "pong";
104 }
105 if ($command == "disconnectDB") {
106 disconMySQL();
107 return;
108 } else {
109 echo "Command not recognized: ".$command;
110 }
111}
112?>