forked from AndyNovo/heroku-play
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.php
32 lines (26 loc) · 1.48 KB
/
api.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
<?php
//this is the basic way of getting a database handler from PDO, PHP's built in quasi-ORM
$dbhandle = new PDO("sqlite:scrabble.sqlite") or die("Failed to open DB");
if (!$dbhandle) die ($error);
//this is a sample query which gets some data, the order by part shuffles the results
//the limit 0, 10 takes the first 10 results.
// you might want to consider taking more results, implementing "pagination",
// ordering by rank, etc.
$query = "SELECT rack, words FROM racks WHERE length=7 and weight <= 10 order by random() limit 0, 10";
//this next line could actually be used to provide user_given input to the query to
//avoid SQL injection attacks
$statement = $dbhandle->prepare($query);
$statement->execute();
//The results of the query are typically many rows of data
//there are several ways of getting the data out, iterating row by row,
//I chose to get associative arrays inside of a big array
//this will naturally create a pleasant array of JSON data when I echo in a couple lines
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
//this part is perhaps overkill but I wanted to set the HTTP headers and status code
//making to this line means everything was great with this request
header('HTTP/1.1 200 OK');
//this lets the browser know to expect json
header('Content-Type: application/json');
//this creates json and gives it back to the browser
echo json_encode($results);
?>