每次填写表格,系统都会向表格中插入两次数据?为什么会这样?
// This checks if variabes are not empty, and if username is less than 11 characters long.
if (!empty($username) && !empty($password) && !empty($message) && strlen($username) < 11) {
// Shortcut for our ID generator function.
$ID = generateID();
// Now lets insert (register the account) these datas to our database.
$insert = $connect->prepare(
"INSERT INTO users (
username,
password,
message,
`date`,
`time`,
id
) VALUES (
:username,
:password,
:message,
CURDATE(),
CURTIME(),
:id
)");
// Executing in array, because if we binded all these variables, it would look very bad.
$insert->execute(array(
':username' => $username,
':password' => $password,
':message' => $message,
':id' => $ID
));
if (!$insert->execute()) {
print_r($insert->errorInfo());
}
}
// Let's check if errors is not empty.
else if (!empty($errors))
{
// Now let's use a loop to get all of the error messages set in the array.
foreach ($errors as $error) {
echo $error;
}
}
我对 PDO 很陌生,这是我第一次完成 PDO 连接、执行、查询。我没看出有什么问题吗?谢谢。
生成标识函数
$nums = substr(hash('sha512', '123456789'), 0, 20);
$ID = str_shuffle($nums);
return $ID;
处理错误函数
function handleErrors() {
// Create new array to handle errors
$errors = array();
// Setting our errors
// If username is empty, set error.
if (empty($username)) {
$errors[] = 'Username is empty';
}
// If password is empty, set error.
else if (empty($password))
{
$errors[] = 'Password is empty';
}
// If username length is more than 11, set error.
else if (strlen($username) > 11)
{
$errors[] = 'Your username is more than 11 characters long';
}
}
杂项:
<?php
require('inc/config.inc.php');
require('inc/session.inc.php');
include('inc/functions.inc.php');
?>
<html>
<h1>Recover</h1>
<br />
<form action="recover.php" method="POST">
Your name: <input type="text" name="username"><br />
Password for this recover: <input type="password" name="password"><br />
Your Message: <input type="text" name="message"><br />
<input type="submit" name="submit"><br />
</form>
<?php
// Check if isset, also fixes the php notices error.
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['message'])) {
// Created shortcuts for the POSTs we currently have.
$username = $_POST['username'];
$password = $_POST['password'];
$message = $_POST['message'];
}
// Let's call our error handling function from functions.inc.php - before we doing the checking.
handleErrors();