我已经开始编写注册脚本了,在脚本中我创建了一个变量名$ message。该变量应该根据不同的条件更新它的字符串值。变量的第一个实例没有条件,在这种情况下,它会在注册页面底部的注册页面上正确回显。回显时,$ message变量的所有其他实例都无法在屏幕上生成文本。我是php的新手,所以我确定它很简单,但由于某些原因我无法弄明白。我认为范围可能是问题,但我认为这只适用于函数而不适用于语句。我不知道。无论如何,这是脚本:
<?php
try{
$dbc = new PDO('mysql:host=localhost;dbname=logreg', 'root', '');
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbc->exec('SET NAMES "utf8"');
} catch (Exception $ex)
{
$error = 'Couldn\'t connect to the databse';
include 'includes/error.html.php';
exit();
}
$sql = 'SELECT name, email, password FROM users';
$result = $dbc->query($sql);
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$names[] = $row['name'];
$email[] = $row['email'];
}
$message = 'Fill out to sign up.';
if (isset($_POST['name'],$_POST['email'], $_POST['password']) and $_POST['name'] and $_POST['email'] and $_POST['password'] !== '')
{
if (in_array($_POST['name'], $names)){
$message = 'That user already exists';
exit();
}
if (in_array($_POST['email'], $email)) {
$message = 'That email already has an account registered';
exit();
}
$sql = $dbc->prepare('INSERT INTO users SET
name = ?,
email = ?,
password = ?');
$name = strtolower($_POST['name']);
$email = strtolower($_POST['email']);
$password = $_POST['password'];
$result = $sql->execute(array(
$name,
$email,
md5($password . 'saltnpepper')
)
);
exit();
}
include 'register.php';
然后,这里是注册页面的代码,其中发生了$ message的回显,并且表单存在。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php echo $message; ?>
<form action="" method="post">
<input type="text" name="name" placeholder="Username">
<input type="text" name="email" placeholder="email">
<input type="password" name="password" placeholder="password">
<input type="submit" value="register">
</form>
</body>
</html>
非常感谢任何帮助!
答案 0 :(得分:1)
您的问题,正如Mark的评论中所述,您使用的是exit()
。摘自手册,内容如下:
终止脚本的执行。关机功能和对象 即使调用exit,也总会执行析构函数。
这意味着每次有exit()
时,它就会在那时停止你的脚本。这意味着它永远不会打印出您的$message
变量。你想要删除那些exit()
,你的脚本就可以了。
此外,您正在以错误的方式进行注册过程。你复杂化了。最常用的方法是运行查询并检查是否使用带有提供数据的where子句返回行。 例如:
$sql = $dbc->prepare('SELECT email,name FROM users WHERE email = ? OR name = ?');
$name = strtolower($_POST['name']);
$email = strtolower($_POST['email']);
$result = $sql->execute(array($name, $email));
$count = $sql->rowCount();
if ($count > 0) {
// user exists
} else {
// user doesn't exist
// add them to db
}
以上只是值得思考的问题:)
答案 1 :(得分:0)
很抱歉,无法使用您的实际数据进行调试,只需在以下代码后立即替换代码:
if (isset($_POST['name'],$_POST['email'], $_POST['password']) and $_POST['name'] and $_POST['email'] and $_POST['password'] !== '')
这个片段:
{
if (in_array($_POST['name'], $names)){
$message = 'That user already exists';
} else {
if (in_array($_POST['email'], $email)) {
$message = 'That email already has an account registered';
} else {
$sql = $dbc->prepare('INSERT INTO users SET
name = ?,
email = ?,
password = ?');
$name = strtolower($_POST['name']);
$email = strtolower($_POST['email']);
$password = $_POST['password'];
$result = $sql->execute(array(
$name,
$email,
md5($password . 'saltnpepper')
)
);
}
}
}