如何使用php存储用户输入信息并存储到管理页面?



请参阅我的PHP代码如下:

是2个文件。我的问题是如何存储用户输入信息并将其存储到管理页面。如果用户输入正确,我如何向他们发出确认信息?我如何创建与获取数据和显示它的管理页面?如何为管理页面设置密码门?请帮忙完成我的作业。谢谢你

文件名称:content.php

<h2>PHP Assignment 1 </h2>
<p><span class="error">* required field </span></p>
<form  action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"  method="post">
First Name:
<input type="text" name="FirstName" value="<?php echo $FirstName;?>"/>
<span class="error">* <?php echo $FirstNameErr;?></span>
<br><br>
Last Name:
<input type="text"name="LastName" value="<?php echo $LastName;?>"/>
<span class="error">* <?php echo $LastNameErr;?></span>
<br><br>
Email Address:
<input type="text" name="EmailAddress" value="<?php echo $EmailAddress;?>"/>
<span class="error">* <?php echo $EmailAddressErr;?></span>
<br><br>
<input name="submit" type="submit" value="Submit"/><br><br>
</form>

文件名称:process.php

<!DOCTYPE HTML>
<html>
<head>
<style>.error {color: #FF0000;} </style>
</head>
<body>
<?php 
$FirstNameErr = $LastNameErr = $EmailAdressErr ="";
$FirstName = $LastName = $EmailAddress = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["FirstName"])) {
$FirstNameErr = "First Name is required";
} else {
$FirstName = test_input($_POST["FirstName"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $FirstName)){
$FirstNameErr = "Only letters and white space allowed";
}
else echo $FirstName;
}
if (empty($_POST["LastName"])) {
$LastNameErr = "Last Name is required";
} else {
$LastName = test_input($_POST["LastName"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $LastName)){
$LastNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["EmailAddress"])){
$EmailAddressErr = "Email Address is required";    
} else {
$EmailAddress = test_input($_POST["EmailAddress"]);
if (!filter_var($EmailAddress, FILTER_VALIDATE_EMAIL)) {
$EmailAddressErr = "Invalid email format";
}
}
}
function test_input($data){
$data= trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
enter code here
<!DOCTYPE HTML>
<html>
<head>
<style>.error {color: #FF0000;} </style>
</head>
<body>
<?php 
$FirstNameErr = $LastNameErr = $EmailAdressErr ="";
$FirstName = $LastName = $EmailAddress = "";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["FirstName"])) {
$FirstNameErr = "First Name is required";
} else {
$FirstName = test_input($_POST["FirstName"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $FirstName)){
$FirstNameErr = "Only letters and white space allowed";
}
else echo $FirstName;
}
if (empty($_POST["LastName"])) {
$LastNameErr = "Last Name is required";
} else {
$LastName = test_input($_POST["LastName"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $LastName)){
$LastNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["EmailAddress"])){
$EmailAddressErr = "Email Address is required";    
} else {
$EmailAddress = test_input($_POST["EmailAddress"]);
if (!filter_var($EmailAddress, FILTER_VALIDATE_EMAIL)) {
$EmailAddressErr = "Invalid email format";
}
}
}
function test_input($data){
$data= trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

在现实世界中,这绝不是正确的方法,但它确实为您提供了一个非常好的起点,包括您可以使用的基础。它基本上涵盖了所有的需求,然而,有一些关键的领域需要改进:管理认证和数据库错误的错误处理等。

下面是它的视频:https://www.youtube.com/watch?v=EmaEYzIkpnY

这个例子有4个文件:

  1. database.php,包含数据库连接助手。数据库连接细节需要更新以匹配您的环境。
  2. forms.php是一个包含变量和表单验证辅助函数的文件。
  3. index.php是你的"前端">
  4. admin.php,这是您登录查看所有记录的提交。
  5. 在简介:

  • 错误简单地存储在一个数组中,然后与辅助函数has_error()get_error()一起呈现。
  • 数据存储与PDO研究一起处理,以及准备好的语句。
  • 门禁管理区域是硬编码的变量值检查,不应该使用。相反,您应该有一个用户表,它将密码存储为散列值,然后您的身份验证过程将根据这些值进行检查并设置会话值。
  • Bootstrap用于基本的UI。

database.php

<?php
/**
* Open a new database connection.
*
* @return PDO
*/
function db_connect() {
$host = 'localhost';
$user = 'root';
$pass = 'mysql';
$name = 'my_table';
try {
return new PDO("mysql:host=$host;dbname=$name;charset=UTF8", $user, $pass);
} catch (PDOException $e) {
die('Database connectuon failed: ' . $e->getMessage());
}
}

forms.php

<?php
/**
* @var array $payload
*/
$payload = [];
/**
* @var string[] $error_bag
*/
$error_bag = [];
/**
* @var bool $success
*/
$success = false;
/**
* Set the global payload array.
*
* @param array $data
*/
function set_payload(array $data) {
global $payload;
$payload = $data;
}
/**
* Add an error to the global error bag.
*
* @param string $name
* @param string $error
*/
function add_error(string $name, string $error) {
global $error_bag;
$error_bag[$name] = $error;
}
/**
* Check if input has errors.
*
* @param string $name
* @return bool
*/
function has_error(string $name) {
global $error_bag;
return array_key_exists($name, $error_bag);
}
/**
* Get the error for input.
*
* @param string $name
* @return null|string
*/
function get_error(string $name) {
global $error_bag;
return has_error($name) ? $error_bag[$name] : null;
}
/**
* Get input from request.
*
* @param string $name
* @param mixed $default
* @return mixed|null
*/
function input(string $name, $default = null) {
global $payload;
return array_key_exists($name, $payload) ? $_POST[$name] : $default;
}

index . php

<?php
require_once 'database.php';
require_once 'forms.php';
if (!empty($_POST)) {
set_payload($_POST);
$first_name = input('first_name');
$last_name = input('last_name');
$email_address = input('email_address');
if (empty(trim($first_name))) {
add_error('first_name', 'Please provide a first name.');
}
if (empty(trim($last_name))) {
add_error('last_name', 'Please provide a last name.');
}
if (empty(trim($email_address)) || !filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
add_error('email_address', 'Please provide a valid email address.');
}
// If empty, assume all fields are valid.
if (empty($error_bag)) {
// Empty payload on success, prevents form values from being filled.
set_payload([]);
$database = db_connect();
$database->exec("CREATE TABLE IF NOT EXISTS submissions (
`id` INT NOT NULL AUTO_INCREMENT,
`first_name` longtext NOT NULL,
`last_name` longtext NOT NULL,
`email_address` longtext NOT NULL,
primary key (`id`)
) CHARACTER SET UTF8 COLLATE utf8_general_ci;");
$query = $database->prepare('INSERT INTO `submissions` (`first_name`, `last_name`, `email_address`) VALUES (:first_name, :last_name, :email_address)');
$query->execute([
':first_name' => $first_name,
':last_name' => $last_name,
':email_address' => $email_address
]);
if ($database->lastInsertId()) {
// Set success flag.
$success = true;
} else {
add_error('database', 'Failed to process submission, please try again later.');
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Submission</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<div class="container my-5">
<h1>PHP Assignment 1 </h1>
<?php if ($success): ?>
<div class="alert alert-success">
<strong>Success!</strong> Your submission has been recieved.
</div>
<?php endif ?>
<?php if (has_error('database')): ?>
<div class="alert alert-danger">
<strong>Uh oh!</strong> <?= htmlspecialchars(get_error('database')); ?>
</div>
<?php endif ?>
<form action="index.php"  method="post">
<div class="mb-3">
<label for="first-name">First name:</label>
<input
type="text"
id="first-name"
name="first_name"
class="form-control <?= has_error('first_name') ? 'is-invalid' : ''; ?>"
value="<?= htmlspecialchars(input('first_name')); ?>">
<?php if (has_error('first_name')): ?>
<div class="invalid-feedback"><?= get_error('first_name'); ?></div>
<?php endif ?>
</div>
<div class="mb-3">
<label for="last-name">Last name:</label>
<input
type="text"
id="last-name"
name="last_name"
class="form-control <?= has_error('last_name') ? 'is-invalid' : ''; ?>"
value="<?= htmlspecialchars(input('last_name')); ?>">
<?php if (has_error('last_name')): ?>
<div class="invalid-feedback"><?= get_error('last_name'); ?></div>
<?php endif ?>
</div>
<div class="mb-3">
<label for="email-address">Email address:</label>
<input
type="email"
id="email-address"
name="email_address"
class="form-control <?= has_error('email_address') ? 'is-invalid' : ''; ?>"
value="<?= htmlspecialchars(input('email_address')); ?>">
<?php if (has_error('email_address')): ?>
<div class="invalid-feedback"><?= get_error('email_address'); ?></div>
<?php endif ?>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>

admin.php

<?php
require_once 'database.php';
require_once 'forms.php';
/**
* @var bool $authed
*/
$authed = false;
if (!empty($_POST)) {
set_payload($_POST);
$username = input('username');
$password = input('password');
if (empty(trim($username))) {
add_error('username', 'Please enter your username.');
}
if (empty(trim($password))) {
add_error('password', 'Please enter your password.');
}
if (empty($error_bag) && ($username !== 'test' || $password !== 'password1')) {
add_error('username', 'The details provided were incorrect.');
}
// If empty, assume all fields are valid.
if (empty($error_bag)) {
// Empty payload on success, prevents form values from being filled.
set_payload([]);
// Set success flag.
$authed = true;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin area</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body class="bg-light">
<div class="container my-5">
<?php if ($authed): ?>
<h1>Submission results</h1>
<?php
$database = db_connect();
$results = $database->query('SELECT * FROM `submissions`')->fetchAll();
?>
<table class="table table-striped table-bordered bg-white">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Email address</th>
</tr>
</thead>
<tbody>
<?php if ($results): ?>
<?php foreach($results as $result): ?>
<tr>
<td><?= htmlspecialchars($result['id']); ?></td>
<td><?= htmlspecialchars($result['first_name']); ?></td>
<td><?= htmlspecialchars($result['last_name']); ?></td>
<td><?= htmlspecialchars($result['email_address']); ?></td>
</tr>
<?php endforeach ?>
<?php else:?>
<tr>
<td colspan="4">No results</td>
</tr>
<?php endif ?>
</tbody>
</table>
<?php else: ?>
<div class="row justify-content-center">
<div class="col-lg-4">
<div class="card">
<div class="card-body">
<form  action="admin.php"  method="post">
<div class="mb-3">
<label for="first-name">Username:</label>
<input
type="text"
id="username"
name="username"
class="form-control <?= has_error('username') ? 'is-invalid' : ''; ?>"
value="<?= htmlspecialchars(input('username')); ?>">
<?php if (has_error('username')): ?>
<div class="invalid-feedback"><?= get_error('username'); ?></div>
<?php endif ?>
</div>
<div class="mb-3">
<label for="last-name">Password:</label>
<input
type="password"
id="password"
name="password"
class="form-control <?= has_error('password') ? 'is-invalid' : ''; ?>"
value="<?= htmlspecialchars(input('password')); ?>">
<?php if (has_error('password')): ?>
<div class="invalid-feedback"><?= get_error('password'); ?></div>
<?php endif ?>
</div>
<button type="submit" class="btn btn-primary btn-block">Login</button>
</form>
</div>
</div>
</div>
</div>
<?php endif ?>
</div>
</body>
</html>

相关内容

  • 没有找到相关文章

最新更新