I am very new to PHP and have been attempting to integrate with mysqli. Apparently on line 19 of my code the variable shown is undefined but as far as I can tell I defined it.
Here is the code. I've look around but I can't really find something to isolate this.
<?php
include("connect.php");
$error = "";
if(isset($_POST['submit']))
{
$characterName = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
}
if(strlen($fname) < 3)
{
$error = "Character name is too short";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error = "Please enter a valid email address";
}
else if(strlen($password) < 8)
{
$error = "Password must be more than 8 characters";
}
else if($password === $passwordConfirm)
{
$error = "Password does not match";
}
else if($image = "")
{
$error = "Please upload an Avatar";
}
else
{
$error = "You have successfully registered";
}
?>
Form Code:
<form method="post" action="index.php" enctype="multipart/form-data">
<label>Character Name:</label><br />
<input type="text" name="fname" /><br /><br />
<label>Email:</label><br />
<input type="text" name="email" /> <br /><br />
<label>Password:</label><br />
<input type="password" name="password" /><br /><br />
<label>Reenter Password:</label><br />
<input type="password" name="passwordConfirm" /><br /><br />
<label>Send us an Avatar:</label><br />
<input type="file" name="image" /><br /><br />
<input type="submit" name="submit" value="submit" />
</form>
if(strlen($fname) < 3) {
$error = "Character name is too short";
}
Here you have the error, $fname is not defined. What you there meaning is $_POST['fname'];. Which you stored in $characterName so change it to:
if(strlen($characterName) < 3){
$error = "Character name is too short";
}
Anyway, cause you define your variables only if isset($_POST['submit']), the lines below will fail if it is not set. Here is a example how it would work.
$_POST['submit'] is only defined if you call it with post parameters (formular, ajax..), so if you directly open the php file it wont work. I added a few comments to make it clear.
<?php
include("connect.php");
$error = "";
if(isset($_POST['submit'])) {
//If this block of variable declaration failed it wouldn´t define the variables
$characterName = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
//So we led Php only check the variables if a submit is provided
if(strlen($characterName) < 3) {
$error = "Character name is too short";
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = "Please enter a valid email address";
} else if(strlen($password) < 8) {
$error = "Password must be more than 8 characters";
} else if($password === $passwordConfirm) {
$error = "Password does not match";
} else if($image = "") {
$error = "Please upload an Avatar";
} else {
$error = "You have successfully registered";
}
} else {
//If there is no submit we land here
$error = "No data provided";
}
?>
if submit is not posted then only you receive undefined variables error. In order to avoid those errors. You just change your code like this
if(isset($_POST['submit']))
{
$characterName = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConfirm = $_POST['passwordConfirm'];
$image = $_FILES['image']['name'];
$tmp_image = $_FILES['image']['tmp_name'];
$imageSize = $_FILES['image']['size'];
}
else
{
$error ="Your submit is not posted.";
exit(); //Without it would again trigger the undefined variables.
}
Related
I'm trying to create a PHP registration script using PDO prepared statements with positional placeholders. But the MySQL queries don't execute. var_dump(); doesn't display any error.
I desperately need someone to closely look at my code and explain to me why the queries don't execute.
Below is a rewrite of register.php, which now displays errors, if certain, predefined conditions are not met. However, it doesn't display any error, when the insert or select query fail. var_dump(); doesn't display any error either, even though PDO queries fail to execute.
Please, I need your help to fix this. Your time and input are much appreciated in advance. Thanks.
register.php:
<?php
// include configuration file
require ("includes/config.php");
//Class import for image uploading
//classes is the map where the class file is stored (one above the root)
include ("classes/upload/upload_class.php");
// define variables and set to empty values
$firstnameErr = $lastnameErr = $usernameErr = $genderErr = $passwordErr = $confirmationErr = $emailErr = $birthdayErr = $phoneErr = "";
$firstname = $lastname = $username = $gender = $password = $confirmation = $email = $birthday = $phone = "";
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$firstname = student_input($_POST["firstname"]);
$lastname = student_input($_POST["lastname"]);
$username = student_input($_POST["username"]);
$gender = student_input($_POST["gender"]);
$password = student_input($_POST["password"]);
$confirmation = student_input($_POST["confirmation"]);
$email = student_input($_POST["email"]);
$birthday = student_input($_POST["birthday"]);
$phone = student_input($_POST["phone"]);
// validate submission
if (empty($_POST["firstname"]))
{
$firstnameErr = "First name is required.";
}
else
{
$firstname = student_input($_POST["firstname"]);
}
if(empty($_POST["lastname"]))
{
$lastnameErr = "Last name is required.";
}
else
{
$lastname = student_input($_POST["lastname"]);
}
if(empty($_POST["username"]))
{
$usernameErr = "Username is required.";
}
else if(!empty($_POST["username"]))
{
// validate username
if (!preg_match("/^[a-zA-Z0-9]*$/", $username))
{
$usernameErr = "Username must contain only letters and numbers.";
}
if (strlen($username) < 4 || strlen($username) > 10)
{
$usernameErr = "Username must be from 4 to 10 characters.";
}
}
else
{
$username = student_input($_POST["username"]);
}
if(empty($_POST["gender"]))
{
$genderErr = "Gender is required.";
}
else
{
$gender = student_input($_POST["gender"]);
}
if(empty($_POST["password"]))
{
$passwordErr = "Enter a password.";
}
else if(!empty($_POST["password"]))
{
// validate username
if (!preg_match("/^[a-zA-Z0-9]*$/", $password))
{
$passwordErr = "Password must contain letters, numbers and special characters.";
}
if (strlen($password) < 8 || strlen($password) > 20)
{
$passwordErr = "Password must be from 8 to 20 characters.";
}
}
else if (empty($_POST["confirmation"]))
{
$confirmationErr = "Confirm your password.";
}
else if ($_POST["password"] != $_POST["confirmation"])
{
$confirmationErr = "Password and confirmation don't match.";
}
else
{
$password = student_input($_POST["password"]);
}
if(empty($_POST["email"]))
{
$emailErr = "Your email address is required.";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid email format";
}
else
{
$email = student_input($_POST["email"]);
}
if(empty($_POST["birthday"]))
{
$birthdayErr = "Birthday is required.";
}
else if(!empty($_POST["birthday"]))
{
$today = date("d-m-Y");
$diff = date_diff(date_create($birthday), date_create($today));
if($diff->format('%y%') < 6)
{
$birthdayErr = "You must be at least 6 years old to register.";
}
else
{
$birthday = student_input($_POST["birthday"]);
}
}
if(empty($_POST["phone"]))
{
$phoneErr = "Phone number is required.";
}
else if(!empty($_POST["phone"]))
{
// Don't allow country codes to be included (assumes a leading "+")
if (preg_match('/^(\+)[\s]*(.*)$/',$phone))
{
$phoneErr = "You should not include the country code.";
}
// Remove hyphens - they are not part of a telephone number
$phone = str_replace ('-', '', $phone);
// Now check that all the characters are digits
if (!preg_match('/^[0-9]{10,11}$/',$phone))
{
$phoneErr = "Phone number should be either 10 or 11 digits";
}
// Now check that the first digit is 0
if (!preg_match('/^0[0-9]{9,10}$/',$phone))
{
$phoneErr = "The telephone number should start with a 0";
}
else
{
$phone = student_input($_POST["phone"]);
}
}
else if(!empty($_FILES["userimage"]))
{
//This is the directory where images will be saved
$max_size = 1024*250; // the max. size for uploading
$my_upload = new file_upload;
$my_upload->upload_dir = "images/user/"; // "files" is the folder for the uploaded files (you have to create this folder)
$my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg"); // specify the allowed extensions here
// $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
$my_upload->rename_file = false;
$my_upload->the_temp_file = $_FILES['userimage']['tmp_name'];
$my_upload->the_file = $_FILES['userimage']['name'];
$my_upload->http_error = $_FILES['userimage']['error'];
$my_upload->replace = "y";
$my_upload->do_filename_check = "n"; // use this boolean to check for a valid filename
if ($my_upload->upload()) // new name is an additional filename information, use this to rename the uploaded file
{
$full_path = $my_upload->upload_dir.$my_upload->file_copy;
$imagename = $my_upload->file_copy;
}
else
{
$imagename = "";
}
}
else
{
try
{
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute(student_input($_POST["username"]));
$user = $stmt->fetch(); # get users data
if($user["username"]==$username)
{
$errorMsg[]="Sorry username already exists"; //check condition username already exists
}
else if($user["email"]==$email)
{
$errorMsg[]="Sorry email already exists"; //check condition email already exists
}
else if($user["phone"]==$phone)
{
$errorMsg[]="Sorry, the phone number already exists"; //check condition email already exists
}
else if(!isset($errorMsg)) //check no "$errorMs g" show then continue
{
$new_password = password_hash($password, PASSWORD_DEFAULT); //encrypt password using password_hash()
// insert form input into database
$stmt= $pdo->prepare("INSERT INTO users (firstname, lastname, username, gender, password, email, birthday, phone, userimage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")->execute($data);
// find out user's ID
$stmt = $pdo->query("SELECT LAST_INSERT_ID() AS user_id");
$user_id = $stmt[0]["user_id"];
// redirect to list users page
header("Location: userinfo.php");
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
// render the header template
include("templates/header.php");
// render add user template
include("templates/register-form.php");
// render the footer template
include("templates/footer.php");
?>
I have the following, relevant code in functions.php, which is called by the config.php:
// validate user input
function student_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Another thing: how do I print the errors on the register-form.php right below any existing error's input field?
register-form.php:
<br>
<br>
<h1>Register</h1>
<br>
<form enctype="multipart/form-data" action="register.php" method="post">
<fieldset>
<div class="form-group">
<label>First Name:</label><span class ="error">*</span> <input autofocus class="form-control" name="firstname" placeholder="First Name" type="text"/>
<span class = "error"><?php //echo $errorMsg["firstname"];?></span>
</div>
<div class="form-group">
<label>Last Name:</label><span class ="error">*</span> <input class="form-control" name="lastname" placeholder="Last Name" type="text"/><br />
<span class = "error"><?php //echo $errorMsg["lastname"];?></span>
</div>
<div class="form-group">
<label>Username:</label><span class ="error">*</span> <input class="form-control" name="username" type="text"/><br />
<span class = "error"><?php //echo $errorMsg["username"];?></span>
</div>
<div class="form-group">
<label>Gender:</label><span class ="error">*</span> <select class="form-control" name="gender" value="gender">
<option value="">Select your gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Password:</label><span class ="error">*</span> <input class="form-control" name="password" type="password"/ autocomplete="off"><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Confirm Password:</label><span class ="error">*</span> <input class="form-control" name="confirmation" type="password"/><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Email:</label><span class ="error">*</span> <input class="form-control" name="email" placeholder="Email" type="text"/><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Phone:</label><span class ="error">*</span> <input class="form-control" name="phone" placeholder="Phone" type="tel" min="10" max="11"/><br />
<span class = "error"><?php //echo $error;?></span>
</div>
<div class="form-group">
<label>Date of Birth:</label><span class ="error"></span> <input class="form-control" name="birthday" placeholder="birthday" type="date" /><br />
<span class = "error"><?php //echo $error[birthday];?></span>
</div>
<div class="form-group">
<label>Passport Photo:</label><input class="form-control" name="userimage" id="fileimage" placeholder="Your Photo" type="file"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default" name="Register" value="Register">Register</button>
</div>
</fieldset>
</form>
<div>
or Login
</div>
<br/>
<br>
<br>
I'm trying to create a PHP file of a process form that indicates the required fields when processed. The code that I have is:
<html>
<head>
<style type="text/css">
.error{color: #FF0000;}
</style>
</head>
<body>
<?php
if(isset($_POST['fullname']) && $_POST['fullname'] != "") {
$fullname = $_POST['fullname'];
}
if(isset($_POST['email']) && $_POST['email'] != "") {
$email = $_POST['email'];
}
if(isset($_POST['feedback']) && $_POST['feedback'] != "") {
$text= $_POST['feedback'];
}
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == POST) {
if (empty($_POST["fullname"])){
$nameErr = "Name is required";
} else {
$name = test_input($_POST["fullname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}
?>
<h1>Customer Feedback</h1>
<p1>Please tell us what you think</p1><br><br>
<form method='POST' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>' >
<p1>Your name:</p1><br>
<input type="text" name="fullname" value="<?php echo $fullname; ?>"><br><br>
<p1>Your email address:</p1><br>
<input type="text" name="email" value="<?php echo $email; ?>"><br><br>
<p1>Your feedback:</p1><br>
<textarea rows="5" cols="50" name="feedback"><?php echo $text;?></textarea><br><br>
<input type="submit" Value="Send Feedback"><br><br>
<?php
error_reporting(E_ALL);
$name = $_POST['fullname'];
$email = $_POST['email'];
$feed = $_POST['feedback'];
if (empty($name))
{
echo "Please enter your name, email and feedback.";
}
if (empty($email))
{
echo "Please enter your email and feedback.";
}
if (empty($feed))
{
echo "Please enter feedback.";
}
if (!empty($name) && !empty($email) && !empty($feed))
{
echo "You have inserted the correct data";
}
?>
</form>
</body>
</html>
However, when I run it on Chrome, I got a server error 500 saying that
The website encountered and error while retrieving process_4.php. It maybe down for maintenance or configured incorrectly.
The other PHP files that I've made leading up to this point have all worked correctly and I don't know why this one isn't.
This is my registration form I am using both javascript and php for validating form, javascript code works well in showing validation error messages however somethings wrong with php code,when javascript is disabled php code should show form validation error messages by refrshing page on form submit,but no error messages appear and no data is inserted. On clicking submit, page is reloaded but even form does not appear.
<?php
error_reporting('E_ALL ^ E_NOTICE');
if(isset($_POST['reg'])){
$fn = ucfirst($_POST['fname']);
$ln = ucfirst($_POST['lname']);
$un = $_POST['username'];
$em = $_POST['email'];
$pswd = $_POST['password'];
$d= date("Y-m-d");
if (strlen($fn) < 2 || strlen($fn) > 15) {
$error = "First name must be 2 to 15 characters long";
}
elseif (strlen($ln) < 2 || strlen($ln) > 15) {
$error = "Last name must be 2 to 15 characters long";
}
elseif($em==""){
$error = "Email cannot be empty";
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$er = "Invalid email format";
}
elseif($pswd==""){
$error = "Fill your password";
}
elseif($pswd!=$pswd2){
$error = "Password and Confirm password do no match";
}
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO table1 (username,firstname,lastname,email,password) VALUES (:username,:firstname,:lastname,:email,:password)");
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
}
if ($stmt->rowCount() == 1) {
header("Location:login.php");
}
else {
echo "Error occured please try again.";
}
}
?>
<form action="" method="post">
<input type="text" name="fname" id="fn" placeholder="First Name"/><br />
<input type="text" name="lname" id="ln" placeholder="Last Name"/><br />
<input type="text" name="username" id="un" placeholder="Username" class="username" /><br />
<input type="email" name="email" id="em" placeholder="Email"/> <br />
<input type="password" name="password" id="pswd" placeholder="Password"/><br />
<input type="password" name="password2" id="pswd2" placeholder="Confirm Password"/><br />
<input type="submit" id="submit" name="reg" value="Create an Account">
<center><div id="er"><?php echo $error ?></div></center>
</form>
You should echo $error not $er
<center><div id="er"><?php echo $error; ?></div></center>
You are doing a mistake:
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
You should use 'username' instead of ':username'. like this:
$stmt->execute(array('username'=>$un,'firstname'=>$fn,'lastname'=>$ln,'email'=>$em,'password'=>$pswd));
There are a few inconsistencies in your code.
At the beginnig you assign $_POST['email'] to $em, but later you validate against a variable named $email, which doesn't exist at this point.
$em = $_POST['email'];
.
.
.
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$er = "Invalid email format"; //should maybe be $error
}
Then there is the password-validation:
elseif($pswd!=$pswd2){
$error = "Password and Confirm password do no match";
}
$pswd2 has never been defined in your code.
$stmt ist defined in the else-block of your validation, but you use it for getting the row-count after the validation. So, if any of your if-statements is true, this will cause an error.
It would be better if you change that part of your code to this:
else{
$pswd = password_hash($pswd, PASSWORD_DEFAULT);
$stmt = $db->prepare("INSERT INTO table1 (username,firstname,lastname,email,password) VALUES (:username,:firstname,:lastname,:email,:password)");
$stmt->execute(array(':username'=>$un,':firstname'=>$fn,':lastname'=>$ln,':email'=>$em,':password'=>$pswd));
if ($stmt->rowCount() == 1) {
header("Location:login.php");
}
else {
echo "Error occured please try again.";
}
}
After all it seems like you haven't error reporting activatet.
I am using this script : https://github.com/claviska/simple-php-captcha
To make a captcha in php.
I have this codes :
session_start();
include_once 'simple-php-captcha.php';
$_SESSION = array();
$_SESSION['captcha'] = simple_php_captcha();
$code = $_SESSION['captcha']['code'];
if (isset($_POST['username'])&&isset($_POST['password'])) {
if (!empty($_POST['username']) && !empty($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (isset($_POST['captcha'])&&!empty($_POST['captcha'])) {
$captcha = $_POST['captcha'];
if ($captcha == $code) {
echo "Login";
} else {
$errors[] = "Capcha is Not True.";
}
} else {
$errors[] = "Enter capcha.";
}
} else {
$errors[] = "Enter all.";
}
}
And HTML form :
<form accept="" method="POST">
username: <input type="text" name="username">
password: <input type="password" name="password">
captcha: <input type="text" name="captcha">
<img src="<?php echo $_SESSION['captcha']['image_src']; ?>">
<input type="submit" class="Button" value="submit">
</form>
BUT
The problem is that every time i enter the captcha and submit the form, the newer captcha will be generated and the form allways return NOT TRUE CAPTCHA pm.
For example i open the page, and the captcha for example is : 52111,
(i enter it correct) then i submit, then i see error that the captcha is incorrect, because the newer captcha generated is another one like : 48852.
I mean every time the page generate a newer one , How can i fix this problem??
You should save old captcha value, before check the form:
session_start();
if (!isset($_SESSION['captcha']) {
$_SESSION['captcha'] = simple_php_captcha();
}
$code = $_SESSION['captcha']['code'];
include_once 'simple-php-captcha.php';
if (isset($_POST['username'])&&isset($_POST['password'])) {
if (!empty($_POST['username']) && !empty($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (isset($_POST['captcha'])&&!empty($_POST['captcha'])) {
$captcha = $_POST['captcha'];
if ($captcha == $code) {
echo "Login";
} else {
$errors[] = "Capcha is Not True.";
}
unlink($_SESSION['captcha'])
} else {
$errors[] = "Enter capcha.";
}
} else {
$errors[] = "Enter all.";
}
}
add with JS some query string with current date in the chapacha so the image is deleted from the browser cahce:
$('img').prop('src',+"<?php echo $_SESSION['captcha']['image_src']; ?>?_="+new Date().valueOf())
i am a newbie in this php. i am trying to make some validation for my form which will show the error msg if it exploits my validation rules.
my connection file.
<?php
$con = mysql_connect("localhost","root","") or die('could not connect the server: '. mysql_error());
mysql_select_db("interview",$con);
?>
my validate.php file
<?php
require_once('connect.php');
$realnameErr = $nickErr = $passwordErr = $emailErr = "";
$realname = $nick = $password = $email = "";
?>
my form
<form name='v2' id='login' method='post' action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Login</legend>
<label for='realname' >Real Name*:</label>
<input type='text' name='realname' id='realname' maxlength="50" value="<?php echo $realname;?>" /></br>
<span class="error"><?php echo $realnameErr;?></span>
<br>
<label for='nick' >Nick*:</label>
<input type='text' name='nick' id='nick' maxlength="50" value="<?php echo $nick;?>" /></br>
<span class="error"><?php echo $nickErr;?></span>
<br>
<label for='password' >Password*:</label>
<input type='password' name='password' id='password' maxlength="50" /></br>
<span class="error"><?php echo $passwordErr;?></span>
<br>
<label for='email' >Email*:</label>
<input type='text' name='email' id='email' maxlength="50" value="<?php echo $email;?>"/></br>
</fieldset>
<input type='submit' name='submit' value='submit' />
</form>
validation begins here
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['submit'])) {
if (empty($_POST["realname"]))
{
$realnameErr = "Name is required";
}
else
{
$realname=test_input($_POST["realname"]);
if(!preg_match("/^[a-zA-z ]*$/",$realname))
{
$realnameErr = "only letters and white space allowed";
}}
if(empty($_POST["nick"]))
{
$nickErr = "Nick is required";
}
else {
$nick=($_POST["nick"]);
}
if(empty($_POST["password"]))
{
$passwordErr = "password is required";
}
else {
$password=($_POST["password"]);
}
if(empty($_POST["email"]))
{
$emailErr = "email is required";
}
else {
$email=test_input($_POST["email"]);
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}}
checking then inserting
if((!$realnameErr) && (!$nickErr) && (!$passwordErr) && (!$emailErr)) {
$query="INSERT INTO `main`"."(realname,nick,password,email)". "VALUES". "('$realname','$nick',SHA('$password'),'$email')";
$res=mysql_query($query);
echo '<p>Your account has been Successfully created,You are now ready to login. </p>';
}
}}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
You need to have your working Script before you display your form. Because at the moment, the time you output <span class="error"><?php echo $nickErr;?></span> the variable $nickErr is still empty and therefore does not display anything.
Try this:
// Init
$errors = array();
// Validate Post Data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['submit'])) {
if (empty($_POST["realname"])) {
$errors[] = "Name is required";
} else {
$realname = test_input($_POST["realname"]);
if (!preg_match("/^[a-zA-z ]*$/", $realname)) {
$errors[] = "only letters and white space allowed";
}
}
if (empty($_POST["nick"])) {
$errors[] = "Nick is required";
} else {
$nick = ($_POST["nick"]);
}
if (empty($_POST["password"])) {
$errors[] = "password is required";
} else {
$password = ($_POST["password"]);
}
if (empty($_POST["email"])) {
$errors[] = "email is required";
} else {
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$errors[] = "Invalid email format";
}
}
}
}
// If there is any error
if (sizeof($errors))
{
// display it
echo '<div>Following error(s) occured:<br /><br />'. implode('<br />', $errors) .'</div>';
}
else
{
// proceed with db insert here
}