forked from Headstorm/Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
92 lines (84 loc) · 3.05 KB
/
api.php
File metadata and controls
92 lines (84 loc) · 3.05 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
<?php
/*Doccumentation for how use this REST API is included in the sumbitnums.html file*/
header("Access-Control-Allow-Methods: OPTIONS,GET,POST,PUT,DELETE");
header("Content-Type:application/json"); //sends the http json header to browser
function connect(){
//Connection to my database
$dbServername = "localhost";
$dbUsername = "nurudeen_agb";
$dbPassword = "head.storm";
$dbName = "nurudeen_headstormapi";
$con = mysqli_connect($dbServername,$dbUsername,$dbPassword,$dbName);
//checking if connection to the database was successful
if(!$con){
die("Connection failed: ". mysqli_connect_error());
}
else
print_r ("Connection successful");
echo nl2br("\r\n");
return $con;
}
/*This function retrieves the requsted data from the database and returns the sorted list of numbers*/
function readsortedfromDB($listName){
$con = connect();
$sql = "SELECT * FROM posts WHERE listName = '$listName';";
$result = mysqli_query($con,$sql);
if( $result){
echo " Succesful";
}
else{
echo "Error " .$sql . "<br>" .mysqli_error($con);
}
$jsonResult = mysqli_fetch_assoc($result);
$post = json_decode($jsonResult['nums'], TRUE);
$nums = $post['nums'];
sort($nums);
return $nums;
}
/*This function accepts a JSON formated string of 500 numbers and posts to the database*/
function writetoDB($listName,$nums)
{
$con = connect();
$sql = "INSERT INTO posts (listName, nums)
VALUES ('$listName', '$nums');";
$post = json_decode($nums, TRUE);
$nums2 = $post['nums'];
if ($nums2[499] == NULL){
echo " Please enter 500 numbers";
break;
}
else{
if( mysqli_query($con, $sql)){
echo "Record created Succesfully";
}
else{
echo "Error " .$sql . "<br>" .mysqli_error($con);
}
}
mysqli_close($con);
}
/*This switch statement is responds to the html requests that come through*/
switch($_SERVER['REQUEST_METHOD'])
{
case 'GET':
$listName = $_GET["listName"];
echo nl2br("\r\n");
echo $listName;
$apiresponse = readsortedfromDB($listName);
if($apiresponse == NULL)
echo " List does not exist";
else
print_r($apiresponse);
break;
case 'POST':
if(isset($_POST["listName"]) && isset($_POST["nums"])){
$nameofList = $_POST['listName'];
$inputnums = $_POST['nums'];
writetoDB($nameofList,$inputnums);
}
else
echo "Please enter a 'listName' and your 'nums' string";
break;
default:
}
?>