I've started writing a registration script, and within the script I've created a variable name $message. The variable is supposed to update it's string value based off of different conditions. The first instance of the variable has no condition, and in that case it echos properly on the registration page that is included at the bottom of the registration script. All other instances of the $message variable fail to produce text on the screen when echoed. I'm new to php, so I'm sure it's something simple, though I can't figure it out for some reason. I thought maybe scope is the problem, but I think that only applies to functions and not if statements. I don't know. Anyways, here is the script:
<?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';
Then as well, here is the code for the register page where the echo of $message takes place, and the form exists.
<!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>
Any help is greatly appreciated!
exit();is the problemexit();in a wrong way. just comment all that lines withexitfirstly, and check the logic of your if-else statements and behavior$message, you're usingexit()which will terminate the script. As you want to echo that variable,exit()is causing troubles there. Try commenting those lines and try again.