PHP form vadation - php

I am have created a form and having problems validating it as I am getting a few errors when I try to preview it in the browser.
The errors
Undefined index: username in on line 269
Undefined index: email in on line 270
Undefined index: fname in on line 271
Undefined index: lname in on line 272
Undefined index: pnumber in on line 273
Undefined index: address in on line 274
Undefined index: password in on line 275
**my php scripts starts on line 35 and ends on line 131**
<!--DB connection--> (line 35)
<?php
$localhost = "localhost";
$dbuser = "student";
$dbpass = "student";
$dbname = "Curiosity_Pizza";
$connect = mysqli_connect($localhost,$dbuser,$dbpass)or die ("Could not connect to database!");;
mysqli_select_db($connect, "$dbname" );
?>
<!-- inserting form data in to DB-->
<?php
$username =$_POST['username'];
$email =$_POST['email'];
$fname =$_POST['fname'];
$lname =$_POST['lname'];
$pnumber =$_POST['pnumber'];
$address =$_POST['address'];
$password = sha1($_POST['password']);
$inssert = 'INSERT into client(username, email, fname, lname, pnumber ,address, password) VALUES ("'.$username.'","'.$email.'","'.$fname.'","'.$lname.'", "'.$pnumber.'", "'.$address.'","'.$password.'")';
mysqli_query($connect,$inssert);
?>
<!--Registration Valadation-->
<?php
//define varibles and sst to empty (w3Schhols)
$usernameErr = $emailErr = $fnameErr = $lnameErr = $pnumberErr = $addressErr = $passwordErr = "";
$username = $email = $fname = $lname = $pnumber = $address = $password = "";
if ($_SERVER["REQUEST_METHOD"]== "POST"){
$username = test_input($_POST["username"]);
$email = test_input($_POST["email"]);
$fname = test_input($_POST["fname"]);
$lname = test_input($_POST["lname"]);
$pnumber = test_input($_POST["pnumber"]);
$address = test_input($_POST["address"]);
$password = test_input($_POST["passoerd"]);
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"]== "POST"){
if (empty($_POST["userename"])){
$usernameErr = "Userename is a required field";
}else{
$username = test_input($_POST["username"]);
}
if (empty($_POST["email"])){
$emailErr = "Email is a required field";
}else{
$email = test_input($_POST["email"]);
}
if (empty($_POST["fname"])){
$fnameErr = "First Name is a required field";
}else{
$fname = test_input($_POST["fname"]);
}
if (empty($_POST["lanme"])){
$lnameErr = "Last Name is a required field";
}else{
$lname = test_input($_POST["lname"]);
}
if (empty($_POST["pnumber"])){
$pnumberErr = "Phone Number is a required field";
}else{
$pnumber = test_input($_POST["$number"]);
}
if (empty($_POST["address"])){
$addressErr = "Address is a required field";
}else{
$address = test_input($_POST["address"]);
}
if (empty($_POST["$password"])){
$passwordErr = "Password is a required field";
}else{
$password = test_input($_POST["password"]);
}
} (line 131)
**My html/form not sure if its relevant low**
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" />
<table width="600" border="0">
<tr>
<th><label for="Username">Username:</label></th>
<td><input type="text" name="username" />
<span class="error">*<?php echo $usernameErr;?></span></td>
</tr>
<tr>
<th><label for="email">email:</label></th>
<td><input type="email" name="email" />
<span class="error">*<?php echo $emailErr;?></span></td>
</tr>
<tr>
<th><label for="fname">First Name:</label></th>
<td><input type="text" name="fname" />
<span class="error">*<?php echo $fnameErr;?></span></td>
</tr>
<tr>
<th><label for="lname">Last Name:</label></th>
<td><input type="text" name="lname" />
<span class="error">*<?php echo $lnameErr;?></span></td>
</tr>
<tr>
<th><label for="pnumber">Phone Number:</label></th>
<td><input type="number" name="pnumber" />
<span class="error">*<?php echo $pnumberErr;?></span></td>
</tr>
<tr>
<th><label for="address">Address:</label></th>
<td><input type="text" name="address" />
<span class="error">*<?php echo $addressErr;?></span></td>
</tr>
<tr>
<th><label for="password">Passowrd:</label</th> <td><input type="password" name="password" />
<span class="error">*<?php echo $passwordErr;?></span></td>
</tr>
<tr>
<td><input type="submit" name="Submit"</td>
</tr>
</table>
</form>
I have tried reading the other posts on here but have not found anything that would work.

The errors means that the array does not contain the index. Make sure that your $_POST contains username... etc. Try
print_r($_POST)
And make sure it contains "username."
You can also use
array_key_exists("username", $_POST)
to make sure that $_POST contains username.
array_key_exists: http://php.net/manual/en/function.array-key-exists.php
TL;DR
Make sure $_POST contains "username" and any other index that PHP complains is undefined.

Check on the form that is posting information to make sure that the names match up with the parameters you're using.
For instance, you should have something like <input name='username'> somewhere in your form, etc.
Also, you should always do:
if( isset($_POST[INDEX]) )
{
// Stuff with $_POST[INDEX]
}
to make sure that the POST was successfully received.
Also, you can try using Fiddler:
http://www.telerik.com/fiddler
to figure out what is/isn't being posted.

Don't use $_POST['username'] as it might not contain username, first check if there is actually a value with isset isset($_POST['username']) ? $_POST['username'] : null
or better, create a function to handle input data for example:
<?php
function post($index, $default = null) {
return isset($_POST[$index]) ? $_POST[$index] : $default;
}
//Use it like that:
$username = post('username');
$email = post('email');
$fname= post('fname');
...
Edit: Added more example for better clarity.

Related

How to join PHP with HTML forms to make a working page?

I stuck at creating a form that will work i.e. take user input and insert into DB.
I have a code, that i know works on its own. the PHP code when run bare with hard-coded values, works. FORM without PHP works.
When I put it all together, nope. I would really appreciate any input!
P.S. I know some names might be odd and it overall very simple, but I don't want to spend time on something that might not even work, and I really have to make it working, preferably yesterday.
HTML:
<?php require 'insert.php';?>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Absolute classes registration</h2>
<p><span class = "error">* required field.</span></p>
<form method = "post" action = "<?php
echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Username:</td>
<td><input type = "text" name = "username">
<span class = "error">* <?php echo $usernameErr;?></span>
</td>
</tr>
<tr>
<td>E-mail: </td>
<td><input type = "text" name = "email">
<span class = "error">* <?php echo $emailErr;?></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td> <input type = "text" name = "password">
<span class = "error"><?php echo $passwordErr;?></span>
</td>
</tr>
<td>
<input type = "submit" name = "submit" value = "Submit">
</td>
</table>
</form>
</body>
</html>
PHP:
<?php
require 'dbconn.php';
// define variables and set to empty values
$usernameErr = $emailErr = $passwordErr = "";
$username = $email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "Name is required";
}else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "Password required";
}else {
$password = test_input($_POST["password"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$sql = "INSERT INTO User_tbl (username, password, email) VALUES (:username, :password, :email)";
$stmt = $pdo->prepare($sql);
//$stmt->bindParam(':token',$token,PDO::PARAM_STR);
$stmt->bindParam(':username',$username,PDO::PARAM_STR);
$stmt->bindParam(':password',$password,PDO::PARAM_STR);
//$stmt->bindParam(':fname',$user_fname,PDO::PARAM_STR);
//$stmt->bindParam(':lname',$user_lname,PDO::PARAM_STR);
//$stmt->bindParam(':telephone',$user_telephone,PDO::PARAM_STR);
$stmt->bindParam(':email',$email,PDO::PARAM_STR);
//$token = '436546brty546b45y'; // generate unique token
$username = $_POST["username"];
$password = $_POST["password"]; //encrypt password
//$fname = $_POST['fname'];
//$lname = $_POST['lname'];
//$telephone = $_POST['telephone'];
$email = $_POST["email"];
$stmt->execute();
$stmt->close();
//header('location: welcome.php');
?>
Conn:
<?php
$servername = 'redacted';
$login = 'redacted';
$password = 'redacted';
$DBname = 'redacted';
// Establish database connection.
$pdo = new PDO("mysql:host=$servername;dbname=$DBname", $login, $password);
//print error or success
if ($pdo->connect_error) {
die("Connection failed."/* . $conn->connect_error*/);
}
if ($pdo) {
echo "Connected successfully";
}
?>

PHP connect mysql showing undefined variable

I have a problem, while am connecting phpmyadmin database from my php.
The below code is for form,
<div id="wb_element_instance53" class="wb_element">
<form class="wb_form wb_mob_form" method="post"><input type="hidden" name="wb_form_id" value="18498be5"><textarea name="message" rows="3" cols="20" class="hpc"></textarea>
<table>
<tr>
<th class="wb-stl-normal">Name </th>
<td><input type="hidden" name="wb_input_0" value="Name"><input class="form-control form-field" type="text" value="" name="wb_input_0" required="required"></td>
</tr>
<tr>
<th class="wb-stl-normal">Email </th>
<td><input type="hidden" name="wb_input_1" value="E-mail"><input class="form-control form-field" type="text" value="" name="wb_input_1" required="required"></td>
</tr>
<tr class="area-row">
<th class="wb-stl-normal">Message </th>
<td><input type="hidden" name="wb_input_2" value="Message"><textarea class="form-control form-field form-area-field" rows="3" cols="20" name="wb_input_2" required="required"></textarea></td>
</tr>
<tr class="form-footer">
<td colspan="2"><button type="submit" class="btn btn-default">Submit</button></td>
</tr>
</table>
</form>
<script type="text/javascript">
Then, i tried to connect phpmyadmin database using php code below,
<?php
/*
$connect=mysqli_connect('localhost','root','','Contact_db') ;
if(mysqli_connect_errno($connect))
{
echo 'Failed to connect';
}
// create a variable
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
if (isset($_POST['message'])) {
$message = $_POST['message'];
}
$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES ('$name','$email,'$message')";
//Execute the query
mysqli_query($connect,$sql);
?>
But, the above showing the error:
Notice: Undefined variable: name in this line "$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES ('$name','$email,'$message')";"
Notice: Undefined variable: email in in this line "$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES ('$name','$email,'$message')";"
Notice: Undefined variable: message in in this line "$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES ('$name','$email,'$message')";"
What if the isset() fails??
Repair:
have a $sql only if the params are set..
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message']) ){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES ('$name','$email,'$message')";
//Execute the query
mysqli_query($connect,$sql);
}
The problem is that $_POST search for name of the input. You name is wb_input_0, try this:
if (isset($_POST['wb_input_0'])) {
$name = $_POST['wb_input_0'];
}
And the same for email and message. However i would not advice to name inputs like that
try this:
$email ='';
$name ='' ;
$message ='';
print_r($_POST);//to review is all vars in form.
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
if (isset($_POST['message'])) {
$message = $_POST['message'];
}
if (isset($_POST['name'])) {
$name = $_POST['name'];
}else{
$name = '';
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}else{
$email = '';
}
if (isset($_POST['message'])) {
$message = $_POST['message'];
}else{
$message = '';
}
Do yourself a favour and prepare your statement:
$sql ="INSERT INTO contac_ds ('Name','email','message') VALUES (?,?,?)";
$stmt = mysqli_prepare($connect, $sql);
$name="";
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
$email="";
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
$message="";
if (isset($_POST['message'])) {
$message = $_POST['message'];
}
mysqli_stmt_bind_param($stmt,"sss",$name,$email,$message);
mysqli_stmt_execute($stmt);
Note that your current $_POST won't have those fields because your named them differently (and twice) so you also need to fix that.

PHP Form Validation assistant

I really need a help. I know there are similar help with my, but have tried them out no luck.
Am creating a Registration system with user type using PHP and Mysqli procedural. Am just starting up with PHP so please bear with me.
I need help with form validation... it looks OK to me, but the error is not processing. Below is my register and errMsg code.
Connection Code:
define('HOST','localhost');
define('USERNAME','');
define('PASSWORD','');
define('DBNAME','');
$con=mysqli_connect(HOST,USERNAME,PASSWORD,DBNAME)or die('ERROR WHILE CONNECTING TO DATABASE SERVER');
?>
Registration and errMsg code
<?php
session_start();
if(is_file('include/connection.php'))
include_once('include/connection.php');
else
exit('Database FILES MISSING:(');
?>
<?php $_SESSION['main_title'] = "Registration Page"; ?>
<?php
if(isset($_SESSION['user_type'])){
header('Location: index.php');
}
if(isset($_POST['submit']))
{
extract($_POST);
// $name = $_POST["name"];
// $email = $_POST["email"];
// $password = $_POST["password"];
// $name = mysqli_real_escape_string($con, $name);
// $email = mysqli_real_escape_string($con, $email);
// $password = mysqli_real_escape_string($con, $password);
$created_at = date('Y-m-d');
$queryInsert = "insert into user (name,last_name,user_name,user_type,email,password,created_at) values ('$name','$last_name','$user_name','$user_type','$email','$password','$created_at')";
$resInsert = mysqli_query($con,$queryInsert);
if($resInsert){
$_SESSION['main_notice'] = "Successfully registered, login here!";
header('Location: index.php');
}else{
$_SESSION['main_notice'] = "Some error, try again";
header('Location: '.$_SERVER['PHP_SELF']);
}
}
?>
<?php
if(is_file('include/header.php'))
include_once('include/header.php');
?>
<?php
// define variables and set to empty values
$nameErr = $lnameErr = $userErr = "";
$name = $lname = $user = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// validate first name
if (empty($_POST["name"])) {
$nameErr = "first Name is required";
}else {
$name = test_input($_POST["name"]);
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
// validate last name
if (empty($_POST["lname"])) {
$lnameErr = "Last Name is required";
}else {
$lname = test_input($_POST["lname"]);
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
}
// validate user type
if (empty($_POST["user_name"])) {
$userErr = "Last Name is required";
}else {
$user = test_input($_POST["user_name"]);
}
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$user)) {
$userErr = "Only letters and white space allowed";
}
}//end validate tag
?>
<div>
<form name="register" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return check()">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" value='<?php echo $name ?>'><span style='color: red'>* <?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="last_name" value='<?php echo $lname ?>'><span style='color: red'>* <?php echo $lnameErr;?></span></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user_name" value='<?php echo $user ?>'><span style='color: red'>* <?php echo $userErr;?></span></td>
</tr>
<tr>
<td>User Type</td>
<td>
<select name="user_type" >
<option value="member">Member</option>
<option value="leader">Leader</option>
</select>
</td>
</tr>
<tr>
<td>Email</td>
<td><input type="email" name="email" ></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="password" ></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confirm_password" id="confirm_password" ></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Register"></td>
</tr>
</table>
</form>
</div>
<script>
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// function check(){
// if(document.getElementById('password').value != document.getElementById('confirm_password').value ){
// alert('password not match');
// return false;
// }else{
// return true;
// }
// }
</script>
<?php
if(is_file('include/footer.php'))
include_once('include/footer.php');
?>
Am not sure if am missing something, but when i send the form without any input, it process it on database. And if i put input in just name field, it just refresh and go blank, even the value data doesn't work idea.
I hope have given enough information for your help, please if any question do ask me.
Thanks in advance
The order of your code seems like it may be the issue. You are checking if the $_POST['submit'] is set and then performing your database operations before the section of code which carries out validation. The section which sets the values to empty should come first, the you want to check if $_POST['submit'] is set, and if it is you THEN do the validation within the if statement. So quickly in pseudocode:
include PHP files
check if user is already logged in
initialise variables
if submit is set {
Validate the input
if valid {
Submit to database
} else {
return error messages as needed
}
}
I hope this helps
EDIT:
$stmt = $con->prepare("INSERT INTO user (name, last_name, user_name, user_type, email, password, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $name, $last_name, $user_name, $user_type, $email, $password, $created_at);
$stmt->execute();
$stmt->close();
$con->close();
Also, noticed a few more issues with your other code which may cause you problems.
In the input checks, you are setting variables like $nameErr if the field is invalid. Once you've sorted the code order out though you may find that you have to introduce a check for whether or not you actually have an error at the end of the validation or it will attempt to execute the database section anyway.
The error variables are echo'd to the page but if the all the inputs were acceptable, none of these variables will be defined and PHP might throw errors
Reorganise the code, and then have a careful look at it and think about how the data flow would work when valid and invalid (or null) input is provided.

How to insert data to mysql using php

i have made a registration from (followed e.g from w3schools.com) where they have used the $_SERVER["PHP_SELF"] in the action of form method.
$_SERVER["PHP_SELF"] this helps for validation part but it doesn't allow to insert data into db.
I have also written code for mobile no. where only numbers should be inserted but that is also not working.Please help.
<html>
<head>
<title>Meeting Room Application</title>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $mobErr = $uidErr = $pwdErr = $roleErr = "";
$txtname = $gender = $txtmob = $txteid = $txtuid = $txtpwd = $role = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["txtname"])) {
$nameErr = "Name is required";
} else {
$txtname = test_input($_POST["txtname"]);
// check if name only contains letters and whitespace
if(!preg_match("/^[a-zA-Z ]*$/", $txtname)) {
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["txteid"])) {
$emailErr = "Email is required";
} else {
$txteid = test_input($_POST["txteid"]);
// check if e-mail address is well-formed
if(!filter_var($txteid, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if(empty($_POST["txtmob"])) {
$mobErr = "Mobile is required";
} else {
$txtmob = test_input($_POST["txtmob"]);
//check only numbers are given
if(preg_match("/^d{10}$/", $txtmob)) {
$mobErr = "Only numbers are allowed";
}
}
if(empty($_POST["txtuid"])) {
$uidErr = "User Id is required";
} else {
$txtuid = test_input($_POST["txtuid"]);
}
if(empty($_POST["txtpwd"])) {
$pwdErr = "Password is required";
} else {
$txtpwd = test_input($_POST["txtpwd"]);
}
if(empty($_POST["role"])) {
$roleErr = "Role is required";
} else {
$role = test_input($_POST["role"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<table align="center" cellpadding="5" cellspacing="5">
<tr>
<th colspan="2"><img src="Hitech Logo1.png" alt="HiTech"></th>
</tr>
<tr>
<th colspan="2"><h1>User Registration</h1></th>
</tr>
<tr>
<td colspan="2" align="left"><font color="red">All fields are mandatory</font></td>
</tr>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<tr>
<td>Full Name : </td>
<td><input type="text" name="txtname" value="<?php echo $txtname ?>"> <font color="red"><?php echo $nameErr; ?></td>
</tr>
<tr>
<td>Gender : </td>
<td><input type="radio" name="gender" <?php if(isset($gender) && $gender == "Male") echo "checked"; ?> value="Male">Male
<input type="radio" name="gender" <?php if(isset($gender) && $gender == "Female") echo "checked"; ?> value="Female">Female
<font color="red"><?php echo $genderErr; ?>
</td>
</tr>
<tr>
<td>Mobile No. : (+91)</td>
<td><input type="text" name="txtmob" maxlength="10" value="<?php echo $txtmob ?>">
<font color="red"><?php echo $mobErr; ?>
</td>
</tr>
<tr>
<td>Email Id : </td>
<td><input type="text" name="txteid" value="<?php echo $txteid ?>">
<font color="red"><?php echo $emailErr; ?>
</td>
</tr>
<tr>
<td>User Id : </td>
<td><input type="text" name="txtuid" value="<?php echo $txtuid ?>">
<font color="red"><?php echo $uidErr; ?>
</td>
</tr>
<tr>
<td>Password : </td>
<td><input type="password" name="txtpwd" value="<?php echo $txtpwd ?>">
<font color="red"><?php echo $pwdErr; ?>
</td>
</tr>
<tr>
<td>Role : </td>
<td><input type="radio" name="role" <?php if(isset($role) && $role == "User") echo "checked"; ?> value="User">User
<input type="radio" name="role" <?php if(isset($role) && $role == "Admin") echo "checked"; ?> value="Admin">Admin
<font color="red"><?php echo $roleErr; ?>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" name="btnsave">
</td>
</tr>
</form>
</tr>
</table>
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "testmra"; // Database name
// Connect to server and select databse.
$conn = mysqli_connect($host, $username, $password) or die("cannot connect");
mysqli_select_db($conn, $db_name);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$mobile = mysqli_real_escape_string($conn, $_POST['txtmob']);
$email = mysqli_real_escape_string($conn, $_POST['txteid']);
$username = mysqli_real_escape_string($conn, $_POST['txtuid']);
$userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']);
$role = mysqli_real_escape_string($conn, $_POST['role']);
$res = mysqli_query($conn, "SELECT username FROM trialusers WHERE username='$username'");
$row = mysqli_fetch_row($res);
if($row > 0) {
echo "Username $username has already been taken";
} else {
$sql = "INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')";
if(mysqli_query($conn, $sql)) {
header("location:registration.php");
} else {
die('Error: Cannot connect to db');
}
}
?>
</body>
</html>
Change the last part of your code to this:
<?php
if(!empty($_POST)){
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$mobile = mysqli_real_escape_string($conn, $_POST['txtmob']);
$email = mysqli_real_escape_string($conn, $_POST['txteid']);
$username = mysqli_real_escape_string($conn, $_POST['txtuid']);
$userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']);
$role= mysqli_real_escape_string($conn, $_POST['role']);
$res=mysqli_query($conn,"SELECT username FROM trialusers WHERE username='$username'");
$row=mysqli_fetch_row($res);
if($row>0)
{
echo "Username $username has already been taken";
}
else
{
$sql="INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')";
if (mysqli_query($conn,$sql))
{
header("location:registration.php");
}
else
{
die('Error: Cannot connect to db' );
}
}
}
?>
This will trigger the data insert part only when you actually post data from the form and will remove the error you see. BTW the code you are using is outdated and use a mysql library that is deprecated. Please consider update to PDO
It is not always possible to receive a POST request on your page so keep your bottom PHP code into a condition
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$mobile = mysqli_real_escape_string($conn, $_POST['txtmob']);
$email = mysqli_real_escape_string($conn, $_POST['txteid']);
$username = mysqli_real_escape_string($conn, $_POST['txtuid']);
$userpass = mysqli_real_escape_string($conn, $_POST['txtpwd']);
$role= mysqli_real_escape_string($conn, $_POST['role']);
$res=mysqli_query($conn,"SELECT username FROM trialusers WHERE username='$username'");
$row=mysqli_fetch_row($res);
if($row>0)
{
echo "Username $username has already been taken";
}
else
{
$sql="INSERT INTO newuser (name,gender,contactno,emailid,username,userpass,role)VALUES('$name','$gender','$mobile','$email','$username','$userpass','$role')";
if (mysqli_query($conn,$sql))
{
header("location:registration.php");
}
else
{
die('Error: Cannot connect to db' );
}
}
}

Converting 'eregi_replace' function to 'preg_replace' and a 'mysql_num_rows' parameter fix

I've made a register.php file to sign up for a website I'm currently building. I'm running XAMPP to host my website and test it before I upload it via a paid host. After making the php file with the help of a few video's and online forums I opened it in google chrome and filled out the registration form I had created. But upon pressing 'submit' was presented with the following errors instead of having the user info successfully written into the mysql database.
Deprecated: Function eregi_replace() is deprecated in C:\xampp\htdocs\register.php on line 53
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\register.php on line 56
Deprecated: Function eregi_replace() is deprecated in C:\xampp\htdocs\register.php on line 97
Deprecated: Function eregi_replace() is deprecated in C:\xampp\htdocs\register.php on line 98
Deprecated: Function eregi_replace() is deprecated in C:\xampp\htdocs\register.php on line 99
Deprecated: Function eregi_replace() is deprecated in C:\xampp\htdocs\register.php on line 100
I know that the reason for errors related to the eregi_replace() function is because it is no longer being supported/used by the php language. I also am aware there is an alternative of preg_replace() However the problem stands that as a newbie in the field of php I am not able to come up with a solution. I'm learning a little more everyday but I need this page done quickly to continue on with my website and with school I don't have time to try out so many multiple blocks of code to come up with a solution. I apologize; I'm going to need a little spoon feeding. :/ If you can take my code and tell me how to fix the errors listed above, or even better respond with a fixed copy of the code, It would be very greatly appreciated! Thank you for your time and once again I apologize for my lack of knowledge.
register.php:
<?php
//User check log
//include_once("Scripts/checkuserlog.php");
?>
<?php
// let's initialize vars to be printed to page in the HTML section so our script does not return errors
// they must be initialized in some server environments
$errorMsg = "";
$firstname = "";
$lastname = "";
$email1 = "";
$email2 = "";
$pass1 = "";
$pass2 = "";
// This code runs only if the form submit button is pressed
if (isset ($_POST['firstname'])){
/* Example of cleaning variables in a loop
$vars = "";
foreach ($_POST as $key => $value) {
$value = stripslashes($value);
$vars .= "$key = $value<br />";
}
print "$vars";
exit();
*/
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$firstname = stripslashes($firstname);
$lastname = stripslashes($lastname);
$email1 = stripslashes($email1);
$pass1 = stripslashes($pass1);
$email2 = stripslashes($email2);
$pass2 = stripslashes($pass2);
$firstname = strip_tags($firstname);
$lastname = strip_tags($lastname);
$email1 = strip_tags($email1);
$pass1 = strip_tags($pass1);
$email2 = strip_tags($email2);
$pass2 = strip_tags($pass2);
// Connect to database
include_once "/Scripts/connect_to_mysql.php";
$emailCHecker = mysql_real_escape_string($email1);
$emailCHecker = eregi_replace("`", "", $emailCHecker);
// Database duplicate e-mail check setup for use below in the error handling if else conditionals
$sql_email_check = mysql_query("SELECT email FROM members WHERE email='$emailCHecker'");
$email_check = mysql_num_rows($sql_email_check);
// Error handling for missing data
if ((!$firstname) || (!$lastname) || (!$email1) || (!$email2) || (!$pass1) || (!$pass2)) {
$errorMsg = 'ERROR: You did not submit the following required information:<br /><br />';
if(!$firstname){
$errorMsg .= ' * First Name<br />';
}
if(!$lastname){
$errorMsg .= ' * Last Name<br />';
}
if(!$email1){
$errorMsg .= ' * Email Address<br />';
}
if(!$email2){
$errorMsg .= ' * Confirm Email Address<br />';
}
if(!$pass1){
$errorMsg .= ' * Login Password<br />';
}
if(!$pass2){
$errorMsg .= ' * Confirm Login Password<br />';
}
} else if ($email1 != $email2) {
$errorMsg = 'ERROR: Your Email fields below do not match<br />';
} else if ($pass1 != $pass2) {
$errorMsg = 'ERROR: Your Password fields below do not match<br />';
} else if ($email_check > 0) {
$errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside our database. Please use another.<br />";
} else { // Error handling is ended, process the data and add member to database
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$email1 = mysql_real_escape_string($email1);
$pass1 = mysql_real_escape_string($pass1);
$firstname = eregi_replace("`", "", $firstname);
$lastname = eregi_replace("`", "", $lastname);
$email1 = eregi_replace("`", "", $email1);
$pass1 = eregi_replace("`", "", $pass1);
// Add MD5 Hash to the password variable
$db_password = md5($pass1);
// Add user info into the database table for the main site table(audiopeeps.com)
$sql = mysql_query("INSERT INTO members (firstname, lastname, email, password, sign_up_date)
VALUES('$firstname','$lastname','$email1','$db_password', now())")
or die (mysql_error());
$id = mysql_insert_id();
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
mkdir("members/$id", 0755);
//!!!!!!!!!!!!!!!!!!!!!!!!! Email User the activation link !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$to = "$email1";
$from = "admin#Connect.CloudNine.com";
$subject = "Complete your registration at Cloud Nine";
//Begin HTML Email Message
$message = "Hi $firstname,
Complete this step to activate your login identity at [ yourdomain ].
Click the line below to activate when ready.
localhost/activation.php?id=$id&sequence=$db_password
If the URL above is not an active link, please copy and paste it into your browser address bar
Login after successful activation using your:
E-mail Address: $email1
Password: $pass1
See you on the site!
";
//end of message
$headers = "From: $from\r\n";
$headers .= "Content-type: text\r\n";
mail($to, $subject, $message, $headers);
$msgToUser = "<h2>One Last Step - Activate through Email</h2><h4>OK $firstname, one last step to verify your email identity:</h4><br />
In a moment you will be sent an Activation link to your email address.<br /><br />
<br />
<strong><font color=\"#990000\">VERY IMPORTANT:</font></strong>
If you check your email with your host providers default email application, there may be issues with seeing the email contents. If this happens to you and you cannot read the message to activate, download the file and open using a text editor.<br /><br />
";
include_once 'msgToUser.php';
exit();
} // Close else after duplication checks
} else { // if the form is not posted with variables, place default empty variables
$errorMsg = "Fields marked with an [ * ] are required";
$firstname = "";
$lastname = "";
$email1 = "";
$email2 = "";
$pass1 = "";
$pass2 = "";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome To Cloud Nine</title>
<link href="CSS/register.css" rel="stylesheet" type="text/css">
<link href="CSS/css_boxes_register.css" rel="stylesheet" type="text/css">
<link href="CSS/reg_table_register.css" rel="stylesheet" type="text/css">
</head>
<body>
<!--Floating Dock-->
<div id="floating_dock">
<img src="Images/cloudnine_logo.png" width="220px">
<img src="Images/button.png" width="75" height="50" id="button"></div>
<!--Floating Dock End-->
<!--Content Wrap-->
<div id="container_alt">
<form action="register.php" method="post" enctype="multipart/form-data" class="box">
<h3>Account Registration</h3>
<p> </p>
<p>
<table width="447" border="0" align="center" cellpadding="5" cellspacing="1">
<tr>
<td width="435" align="center" valign="middle"><?php print "$errorMsg"; ?></td>
</tr>
<tr>
<td align="center">First Name</td>
</tr>
<tr>
<td align="center"><input name="firstname" type="text" id="firstname" value="<?php print "$firstname";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center">Last Name</td>
</tr>
<tr>
<td align="center"><input name="lastname" type="text" id="lastname" value="<?php print "$lastname";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center">Password</td>
</tr>
<tr>
<td align="center"><input name="pass1" type="text" id="pass1" value="<?php print "$pass1";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center">Confirm Password</td>
</tr>
<tr>
<td align="center"><input name="pass2" type="text" id="pass2" value="<?php print "$pass2";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center">Email</td>
</tr>
<tr>
<td align="center"><input name="email1" type="text" id="email1" value="<?php print "$email1";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center">Confirm Email</td>
</tr>
<tr>
<td align="center"><input name="email2" type="text" id="email2" value="<?php print "$email2";?>" size="35" maxlength="35"></td>
</tr>
<tr>
<td align="center"><input type="submit" name="submit" value="Submit Form"></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</p>
</form>
</div>
</body>
</html>
No need to do regexp if you don't need it. Change
eregi_replace("`", "", $emailCHecker);
to
str_replace("`", "", $emailCHecker);
Do not use the mysql_* functions since they are deprecated. Use mysqli or PDO or whatever flavor you like but do not use mysql_* anymore!
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL
extension should be used. See also MySQL: choosing an API guide and
related FAQ for more information.

Categories