I am trying to learn PHP and created a simple PHP/MySQL form that does successfully register users but is having 2 issues.
- I can't get the page to redirect successfully to
index.phpafter the user hits "Register" - I thought if a user is registered they would see the message "welcome (name)" when they come back to the
register.phppage because I am trying to use sessions. But once I log in, when I go back toregister.php, the page acts as if I am not registered and just displays the form again.
What am I missing for these two questions?
<?php
session_start();
require_once 'connection.php';
if (isset($_SESSION['username']))
{
echo "welcome $author";
}
?>
<html>
<?php include('includes/header.php'); ?>
<!-- The HTML registration form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br>
Author/Pen Name: <input type="text" name="author" /><br>
Password: <input type="password" name="password" /><br>
Email: <input type="type" name="email" /><br />
Author Bio (optional): <br><textarea name="bio" cols="20" rows="5"></textarea><br>
<input type="submit" name="submit" value="Register" />
<a href="login.php">I already have an account...</a>
</form>
<?php
if (isset($_POST['submit'])) {
## connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
## query database
# prepare data for insertion
$username = $_POST['username'];
$contact = $_POST['author'];
$password = $_POST['password'];
$email = $_POST['email'];
$bio = $_POST['bio'];
# check if username and email exist else insert
// u = username, e = emai, ue = both username and email already exists
$exists = "";
$result = $mysqli->query("SELECT username from user WHERE username = '{$username}' LIMIT 1");
if ($result->num_rows == 1) {
$exists .= "u";
}
$result = $mysqli->query("SELECT email from users WHERE email = '{$email}' LIMIT 1");
if ($result->num_rows == 1) {
$exists .= "e";
}
if ($exists == "u") echo "<p><b>Error:</b> Username already exists!</p>";
else if ($exists == "e") echo "<p><b>Error:</b> Email already exists!</p>";
else if ($exists == "ue") echo "<p><b>Error:</b> Username and Email already exists!
</p>";
else {
# insert data into mysql database
$sql = "INSERT INTO `user` (`username`, `author`, `password`, `email`, `bio`)
VALUES ('{$username}', '{$contact}', '{$password}', '{$email}', '{$bio}')";
if ($mysqli->query($sql)) {
header("Location: site.com/index.php");
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
}
?>