-
Notifications
You must be signed in to change notification settings - Fork 1
/
addProjectToDb.php
executable file
·59 lines (50 loc) · 2.24 KB
/
addProjectToDb.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
<?php
$sizeGroups = $_REQUEST['sizeGroups'];
$projectName = $_REQUEST['projectName'];
$studentNames = json_decode($_POST['studentNames']);
$weights = json_decode($_POST['weights']);
$attributes = json_decode($_POST['attributes']);
function generateRandomString($length = 20) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$projectID = generateRandomString();
$authorID = generateRandomString();
$db = new PDO('mysql:host=localhost;dbname=group_maker', 'root', 'password'); //get db connection
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("INSERT INTO classes(classID, className, sizeGroups, authorID) VALUES(:classID, :className, :sizeGroups, :authorID)"); //prepare insert
$data = array(':className' => $projectName, ':classID' => $projectID, ':sizeGroups' => $sizeGroups, ':authorID' => $authorID); //array containing data
try {
$stmt->execute($data);
}
catch (PDOException $e) {
echo $e->getMessage();
}
for($i = 0; $i < sizeof($studentNames); $i++){
$stmt = $db->prepare("INSERT INTO students(name, class, numAttributes) VALUES(:name, :class, :numAttributes)"); //prepare insert
$data = array(':name' => $studentNames[$i], ':class' => $projectID, ':numAttributes' => sizeof($attributes)); //array containing data
try {
$stmt->execute($data);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
$stmt = "CREATE TABLE `$projectID` (`id` INT(11) NOT NULL AUTO_INCREMENT,`attribute` VARCHAR(99) NOT NULL ,`weight` INT(11) NOT NULL ,`studentIndex` INT(11) NOT NULL ,`studentWeight` INT(11) NOT NULL ,PRIMARY KEY (`id`) )";
$db->exec($stmt); //creates new table for project
for($i = 0; $i < sizeof($attributes); $i++){
$stmt = $db->prepare("INSERT INTO $projectID(attribute, weight, studentIndex) VALUES(:attribute, :weight, :studentIndex)"); //prepare insert
$data = array(':attribute' => $attributes[$i], ':weight' => $weights[$i], ':studentIndex' => -1); //array containing data
try {
$stmt->execute($data);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
echo "$projectID;$authorID";
?>