We start by creating a database table. This is very important for web applications, because web applications can’t store state in memory, like desktop applications.
CREATE TABLE `fib` (
`n` INT NOT NULL,
`fib` INT NOT NULL,
PRIMARY KEY (`n`)
);
Now we write the PHP code. You can write the HTML form yourself, it’s not that hard.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include "config.php"; | |
$n = $_GET['n']; | |
if ($n == 1) { | |
echo "fib($n) == 1"; | |
mysql_query("REPLACE INTO `fib` (`n`, `fib`) VALUES ('1','1')"); | |
} | |
else if ($n == 2) { | |
echo "fib($n) == 1"; | |
mysql_query("REPLACE INTO `fib` (`n`, `fib`) VALUES ('2','1')"); | |
} | |
else { | |
$i = 3; | |
while ($i <= $n) { | |
$res = mysql_query("SELECT `fib` FROM `fib` WHERE `n` = '$i'"); | |
if ($res) { | |
$row = mysql_fetch_assoc($res); | |
if (!$row['fib']) { | |
$a = $i - 1; | |
$res = mysql_query("SELECT `fib` FROM `fib` WHERE `n` = '$a'"); | |
if ($res) { | |
$row = mysql_fetch_assoc($res); | |
$f1 = $row['fib']; | |
} | |
$b = $i - 2; | |
$res = mysql_query("SELECT `fib` FROM `fib` WHERE `n` = '$b'"); | |
if ($res) { | |
$row = mysql_fetch_assoc($res); | |
$f2 = $row['fib']; | |
} | |
$fib = $f1+$f2; | |
mysql_query("REPLACE INTO `fib` (`n`, `fib`) VALUES ('$i','$fib')"); | |
} | |
} | |
$i++; | |
} | |
$res = mysql_query("SELECT `fib` FROM `fib` WHERE `n` = '$n'"); | |
if ($res) { | |
$row = mysql_fetch_assoc($res); | |
echo "fib($n) == " . $row['fib']; | |
} | |
} | |
?> |
Do you write code like this? I know I do.