Source Code for /public/07-storing-data/index.php
<?php
require('../inc/functions.php');
add_header('Lesson 7: Storing Data');
?>
<div class="objectives">
<h2>Objectives</h2>
<ul>
<li>...</li>
<li>...</li>
</ul>
</div>
<h2 id="storing-data">Storing Data</h2>
<p>
Your PHP code can access data stored on your server, whether or not that data is directly
accessible to the user. In these examples, we'll be using data stored in files in our
<code>private/</code> directory, outside of our webroot. On <em>this</em> site,
<a href="/appendix-quine/">you've been given access to the <code>private/</code> directory</a>,
but on a real website you normally wouldn't!
</p>
<p class="tip">
Many websites store their data in a <em>relational database</em> like MySQL, MariaDB,
or PostgreSQL. These are a highly-efficient way or storing, searching, and sorting
large volumes of data, but have a significant learning curve (and there are lots more
things that can "go wrong"). This lesson will only discuss storing data in <em>files</em>.
</p>
<h2 id="counter">Counting Clicks</h2>
<p>
A popular widget is a "clap counter", where users can click on a counter to increment it
and show support for a page. <code>clap.php</code> is a basic example:
</p>
<?php code_block_from_file( '07-storing-data/clap.php', 'php' ); ?>
<p>
Here's what's going on:
</p>
<ul>
<li>
We define a function, <code>get_claps</code>, which returns the current clap count. It
does this by loading the number in the file <code>private/clap-count.txt</code>, if it
exists (it returns 0 otherwise).
</li>
<li>
A form is displayed with a button showing the current number of claps. Clicking the button
submits the form.
</li>
<li>
When the form is submitted, some PHP code loads the current clap count, increments it by
one, and then redirects the user back to the same page.
</li>
<li>
When the page is reloaded, the new clap count is displayed.
</li>
</ul>
<p class="tip">
...
</p>
<?php
add_footer();
?>