forked from railsbridge/docs
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcreating_a_data_class.step
106 lines (83 loc) · 2.27 KB
/
creating_a_data_class.step
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
96
97
98
99
100
101
102
103
104
105
106
goals do
goal "Write a class to get our data"
goal "Display the topics on a web page"
message "A class is a special piece of code for performing a given task"
end
steps do
step do
message "Create a new file called `TopicData.php` in the `public` directory"
message "Type the following to create our empty class:"
source_code :php, <<-PHP
<?php
class TopicData {
// CLASS CONTENTS GO HERE
}
?>
PHP
end
step do
message "Now create a constructor that will assign a PDO instance to a class variable:"
source_code :php, <<-PHP
<?php
class TopicData {
protected $connection;
public function __construct($pdo)
{
$this->connection = $pdo;
}
}
?>
PHP
end
step do
message "Next lets make the class fetch all of our topics:"
source_code :php, <<-PHP
<?php
class TopicData {
protected $connection;
public function __construct($pdo)
{
$this->connection = $pdo;
}
public function getAllTopics()
{
$query = $this->connection->prepare("SELECT * FROM topics");
$query->execute();
return $query;
}
}
?>
PHP
tip "Notice how we use the same `SELECT` as in the previous section"
end
step do
message "Now we can use the data class in `index.php`, to get our topics:"
source_code :php, <<-PHP
<?php
require 'TopicData.php';
$pdo = new PDO("mysql:host=localhost;dbname=suggestotron", "root", "root");
$data = new TopicData($pdo);
$topics = $data->getAllTopics();
PHP
message "Now `$topics` is a database result object containing our topics."
end
step do
message "Now we have our topics lets display them by using a `foreach` to iterate over them:"
source_code :php, <<-PHP
foreach ($topics as $topic) {
echo "<h3>" .$topic['title']. " (ID: " .$topic['id']. ")</h3>";
echo "<p>";
echo nl2br($topic['description']);
echo "</p>";
}
PHP
end
step do
message "To see what this looks like, refresh the application in your browser!"
img src: "img/List_of_topics.png", alt: "List of topics"
end
end
explanation do
message "With just these few lines of code we are able to connect to our database, fetch our data, and dynamically create an HTML page. *How neat is that?*"
end
next_step "adding_topics"