To understand the basic workings of PHP I wrote a test page where one can create, load and edit entries (name-info-pairs) in a list.
It would be cool if you could give me some advice on that to improve.
<?php
class User {
public $name;
public $info;
Public function __construct($name, $info){
$this->name = $name;
$this->info = $info;
}
}
function show_user_radio_button($user) {
return '<input type="radio" name="load" value="' .
$user->name .'">' . $user->name . "<br>\n";
}
function read_user_from_text_line($line) {
$cells = explode(",", $line);
return new User($cells[0], $cells[1]);
}
function user_to_text_line($user) {
return $user->name . ',' . $user->info;
}
function load_all_users() {
$contents = file_get_contents('user_database.csv');
$lines = array_filter(explode("\n", $contents));
$allUsers = array();
foreach ($lines as $line)
$allUsers[] = read_user_from_text_line($line);
return $allUsers;
}
function save_all_users($allUsers) {
$contents = '';
foreach ($allUsers as $user)
$contents .= user_to_text_line($user) . "\n";
file_put_contents('user_database.csv', $contents);
}
function save_user($newUser) {
$allUsers = load_all_users();
$replaced = false;
for ($i = 0; $i < count($allUsers); $i++) {
$user = $allUsers[$i];
if ($newUser->name === $user->name) {
$allUsers[$i] = $newUser;
$replaced = true;
}
}
if (!$replaced) {
$allUsers[] = $newUser;
}
save_all_users($allUsers);
}
function loadUser($name) {
$allUsers = load_all_users();
foreach ($allUsers as $user)
if ($user->name === $name) return $user;
return new User('', '');
}
function sanitize($str) {
return filter_var($str, FILTER_SANITIZE_EMAIL);
}
$newName = sanitize($_POST['name']);
$newInfo = sanitize($_POST['info']);
if ($newName && $newInfo)
save_user(new User($newName, $newInfo));
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>basic form to create and edit entries in a text file</title>
</head>
<body>
from database:<br>
<form name="load" action="index.php" method="get">
<?php
$allUsers = load_all_users();
foreach ($allUsers as $user)
echo show_user_radio_button($user);
echo '<input type="submit" value="load">';
?>
</form>
<br>
<br>
-------
<br>
<br>
edit or create<br>
<form name="save" action="index.php" method="post">
<?php
$user = loadUser($_GET['load']);
echo 'name: <input type="text" name="name" value="' .
$user->name . '"><br>';
echo 'info: <input type="text" name="info" value="' .
$user->info . '"><br>';
?>
<input type="submit" value="save">
</form>
</body>
</html>