Creating a registration page in PHP - php

Hi guys so im creating this registration page for my website in php..This is the PHP script
# Script 9.5 - register.php #2
// This script performs an INSERT query to add a record to the users table.
$page_title = 'Register';
include ('includes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Initialize an error array.
// Check for a name:
if (empty($_POST['name'])) {
$errors[] = 'You forgot to enter your name.';
} else {
$n = mysqli_real_escape_string($dbh, trim($_POST['name']));
}
// Check for an email:
if (empty($_POST['email'])) {
$errors[] = 'You forgot to enter your email.';
} else {
$e = mysqli_real_escape_string($dbh, trim($_POST['email']));
}
// Check for a password and match against the confirmed password:
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = 'Your password did not match the confirmed password.';
} else {
$p = mysqli_real_escape_string($dbh, trim($_POST['pass1']));
}
} else {
$errors[] = 'You forgot to enter your password.';
}
// Check for contact number:
if (empty($_POST['contact_no'])) {
$errors[] = 'You forgot to enter your contact no.';
} else {
$cn = mysqli_real_escape_string($dbh, trim($_POST['contact_no']));
}
if (empty($errors)) { // If everything's OK.
require 'connect_db.php';
$conn= mysqli_connect('*****' , '*****', '*****' , '*****' ,****);
// Make the query:
$q = ("INSERT INTO register_user(name, email, pass, contact_no) VALUES ('$n', '$e','$p','$cn')");
$r = #mysqli_query ($dbh, $q);// Run the query.
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Thank you!</h1>
<p>You are now registered. </p>
<p>Login </p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbh) . '<br/><br/> Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbh); // Close the database connection.
// Include the footer and quit the script:
include ('includes/footer.html');
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br>';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br>";
}
echo 'Please try again.</p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbh); // Close the database connection.
But the thing is once i register this is the output:
System Error
You could not be registered due to a system error. We apologize for any inconvenience.
Query: INSERT INTO register_user(name, email, pass, contact_no) VALUES ('', '','','')
so im kindly would glad for any assistance

You're calling mysqli_real_escape_string() BEFORE you establish your DB connection. This is not permitted. You MUST have a connection before doing the escape operations.
That means every single one of your form fields is going to be a boolean FALSE value, which signifies failure.
Your code should be structured
1. connect to db
2. process form inputs
3. if form inputs ok, insert into db
You've got #1 and #2 reversed.

Related

My code is showing no errmsg but is not inserting any data into database

So I am trying to make a simple e-commerce site. Once I submit the form (btn-submit), I am not able to insert any data to my database. Only the address and contact number verification works.
Here is my code:
if ( isset($_POST['btn-submit']) ) {
// clean user inputs
$oadd = trim($_POST['oadd']);
$oadd = strip_tags($oadd);
$oadd = htmlspecialchars($oadd);
$contact = trim($_POST['contact']);
$contact = strip_tags($contact);
$contact = htmlspecialchars($contact);
// address validation
if (empty($oadd)) {
$error = true;
$oaddError = "Please enter a valid address.";
} else if (strlen($oadd) < 5) {
$error = true;
$oaddError = "Please enter a valid address.";
}
// contact number validation
if (empty($contact)) {
$error = true;
$contactError = "Please enter your contact number.";
} else if (strlen($contact) < 7) {
$error = true;
$contactError = "Contact number must have atleast 7 digits.";
} else if (!preg_match("/^[0-9 ]+$/",$lname)) {
$error = true;
$lnameError = "Please enter a valid contact number.";
}
// if there's no error, continue to place order
if( !$error ) {
$query = 'INSERT INTO cust_order(Order_Date, Order_Status, Order_Total , Address, Contact_No) VALUES (CURDATE(), "in process" , (SELECT SUM(p.Product_Price) FROM cart c, product p WHERE c.Prod_ID = p.Product_ID and c. User_ID = "'.$userRow['User_ID'].'"),"'.$oadd.'","'. $contact.'")';
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Your order has been placed. To view the details, go to your order history";
unset($oadd);
unset($contact);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong. Please try again later.";
}
}
}
What could possibly be wrong with my code? I did similar queries in the other pages but this is the only one not working. Any help would be greatly appreciated! Thanks in advance!
Try to understand the code flow:
if( !$error ) {
// This will only works when **$error is false and the not of false is true**, otherwise this block does not execute
}
So this code works only when there is no validation error occurs in your code and $error contains false
//$userRow is not define any where...
//to check error occur or not :
echo $error;
if(!$error)
{
echo "IN IF";
//also go with die..
$res = mysql_query($query) or die();
}
else
{
echo "IN ELSE";
}

Trying to get Unique entries set right for my form

so I have searched this problem and found similar ones, but I'm not sure of how to translate their solutions into mine - mainly because I'm a noob in PHP. I'm working on it. Bear with me. I appreciate the help!
Right now, I am trying to make it so my form will not allow duplicate entries for the email column in phpmysql. So far, I went into the structure tab there, and made it unique. Pretty much viola. However, I would like the error message to display on the same page when the form is submitted, instead of reloading it and giving the message. Also, I would like to customize the message. Seeing as its a phpmysql related error, I'm not sure if I would do that with PHP coding, or somewhere in there.
Thanks guys. I appreciate the help.
<?php
function checkField($v){
return (isset($v) && $v === false) ? true: false;
}
function startMysql(){
$con=mysqli_connect("localhost", "shiftedr_admin", "passwerd", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return null;
}
return $con;
}
// function closeMySql($connection){
// mysqli_close($connection);
// }
function formcheck(){
$con=mysqli_connect("localhost", "shiftedr_admin", "shithead1", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
if (isset($_POST['submitted'])){
$form = null;
if (empty($_POST['fullname'])){
$form['fullnameflag'] = false;
}
if (empty($_POST['email'])){
$form['emailflag'] = false;
}
if (empty($_POST['password'])){
$form['passwordflag'] = false;
}
if (empty($_POST['pwc'])){
$form['pwcflag'] = false;
}
if (empty($_POST['userbday'])){
$form['userbday'] = false;
}
if (empty($_POST['gender'])){
$form['genderflag'] = false;
}
if ($_POST['password'] != $_POST['pwc']){
$form['fixpasswordconfirm'] = false;
}
/*$query = mysql_query ("SELECT * FROM users2 WHERE email = '". Email'" ."'");
if (mysql_num_rows($query) > 0)
{
echo 'Email Address is Already In Use.';
}*/
if (empty($form)) { // all fields correct at this point, do database stuff
$sql="INSERT INTO Users2 (fullname, Email, Password, userbday, Gender) VALUES ('".$_POST['fullname']."','".$_POST['email']."','".$_POST['password']."','".$_POST['userbday']."','".$_POST['gender']."')";
if (!mysqli_query($con,$sql)){
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
}
mysqli_close($con);
return $form;
}
}
//// / include("myfunctions.php");
?>
I am guessing you have two pages - myform.php and process.php or something similar so try doing this
<?php
$error = null;
if( isset( $_POST['submitted'] ) ) // Same as your check is submitting if
{
// Below is an example fail
if( empty( $_POST['fullname'] ) ) $error = 1;
// So for the email address failing you would put
if( mysql_num_rows($query) > 0 ) $error = 2;
if(! $error )
{
// all good no errors here so do database stuff....
}
else
{
header("Location: form.php?error=$error"); // return the error code to previous page
}
}
?>
Were one could be an empty field or could be fullname is empty and two is used email address or something similar and on your myform.php page have
<?php
if( isset( $_GET['error'] ) )
{
switch ( $_GET['error'] )
{
case 1 : echo "One of the fields is empty"; break;
case 2 : echo "Your email address has already been used"; break;
default : echo "Unknown error occured";
}
}
?>

Inserting PHP Session Variables into MySQL Database

I am having issues with my PHP code. I am trying to insert data into a mysql database using two session variables that I will need at a later time in the form. However whenever I submit the form I am returned with a "Unknown column in 'field list'" error.
The code is lengthy but you will likely need all of it to understand the issue.
<?php
session_start();
// Check for hazards and put them in an array if there is one selected
if($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../mysqli_connect.php'); //connect to the db
//Check for offender first name
if (empty($_POST['pris_firstname'])) {
$errors[] = 'You forgot to enter offender first name.';
} else {
$prisf=$_POST['pris_firstname'];
}
//Check for offender last name
if (empty($_POST['pris_lastname'])) {
$errors[] = 'You forgot to enter offender last name.';
} else {
$prisl=$_POST['pris_lastname'];
}
//Check for offender date of birth
$dob = ($_POST['pris_dateofbirth']);
//Check for offender phone number
if (empty($_POST['pris_phonenum'])) {
$errors[] = 'You forgot to enter offender Phone Number.';
} else {
$prisphone=trim($_POST['pris_phonenum']);
}
//Check for offender address
if (empty($_POST['pris_address'])) {
$errors[] = 'You forgot to enter offender Address.';
} else {
//$prisaddress=trim($_POST['pris_address']);
foreach($_POST["pris_address"] as $value) {
$prisaddress .= $value . '\n';
}
}
//Check for offender next of kin first name
if (empty($_POST['pris_kinfirstname'])) {
$errors[] = 'You forgot to enter next of kin first name.';
} else {
$kinfirst=trim($_POST['pris_kinfirstname']);
}
//Check for offender next of kin last name
if (empty($_POST['pris_kinlastname'])) {
$errors[] = 'You forgot to enter next of kin last name.';
} else {
$kinlast=trim($_POST['pris_kinlastname']);
}
//Check for offender next of kin phone number
if (empty($_POST['pris_kinphone'])) {
$errors[] = 'You forgot to enter next of kin area code.';
} else {
$kinphone=trim($_POST['pris_kinphone']);
}
if (empty($_POST['pris_kinrelation'])) {
$errors[] = 'You forgot to enter next of kin relation.';
} else {
$kinrelation=trim($_POST['pris_kinrelation']);
}
//Check for offender next of kin address
if (empty($_POST['pris_kinaddress'])) {
$errors[] = 'You forgot to enter next of kin street address.';
} else {
foreach($_POST["pris_kinaddress"] as $value2) {
$kinaddress .= $value2 . '\n';
}
}
if (empty($errors)) { //if everyhing is ok
$q = "INSERT INTO prisoner_profile (pris_status,
pris_firstname,
pris_lastname,
pris_dateofbirth,
pris_phonenum,
pris_address,
pris_kinfirstname,
pris_kinlastname,
pris_kinphone,
pris_kinaddress,
pris_kinrelation
) VALUES (
'$status',
".$_SESSION['pris_firstname'].", ".$_SESSION['pris_lastname'].",
'$dob',
'$prisphone',
'$prisaddress',
'$kinfirst',
'$kinlast',
'$kinphone',
'$kinaddress',
'$kinrelation'
)";
$r = #mysqli_query ($dbc, $q); //Run the query.
Hope someone can help!
The error is pretty much self-explanatory, it means that you have got a column name wrong in your database. I recomend you echo out the error for your query just for this case as:
$r = mysqli_query ($dbc, $q) or die (mysqli_error());
One of the columns that are listed in your INSERT statement does not actually exist in the prisoner_profile. Check your table schema.
The one obvious issue I can see here is that you haven't handled the escape characters in your query, and you have used a few \n characters in your code.
Use mysqli_real_escape_string to handle that when inputting the data to the database.
Something like
$q = mysqli_real_escape_string($q);

table just inserts one row. there is an auto increment id

This is my registration code.
Once I enter the fields in the form it shows me registration successful but adds blank data in my database table. It adds number 0 in my mobileno column.
Please help me here asap
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['mobileno'])) {//if no name has been supplied
$error[] = 'Please Enter a Mobile Number ';//add to array "error"
} else {
$name = $_POST['mobileno'];//else assign it a variable
}
if (empty($_POST['fname'])) {//if no name has been supplied
$error[] = 'Please Enter a First name ';//add to array "error"
} else {
$name = $_POST['fname'];//else assign it a variable
}
if (empty($_POST['lname'])) {//if no name has been supplied
$error[] = 'Please Enter a Last name ';//add to array "error"
} else {
$name = $_POST['lname'];//else assign it a variable
}
if (empty($_POST['email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA- Z0-9\._-]+)+$/", $_POST['email'])) {
//regular expression for email validation
$Email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwd1'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['passwd1'];
}
if (empty($_POST['passwd2'])) {
$error[] = 'Please Verify Your Password ';
} else {
$Password = $_POST['passwd2'];
}
if (empty($error)) //send to Database if there's no error '
{ //If everything's OK...
// Make sure the mobile no is available:
$query_verify_mobileno = "SELECT * FROM userdtls WHERE mobileno = '$mobileno'";
$result_verify_mobileno = mysqli_query($dbc, $query_verify_mobileno);
if (!$result_verify_mobileno)
{//if the Query Failed ,similar to if($result_verify_mobileno==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_mobileno) == 0) { // IF no previous user is using this number .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO userdtls (`mobileno`, `pass`, `fname`, `lname`, `email`, `activation`) VALUES ( '$mobileno', '$passwd1', '$fname', '$lname', '$email', '$activation')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
mail($Email, 'Registration Confirmation', $message, 'From: rahul19dj#gmail.com');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to '.$email.' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The mobile number is not available.
echo '<div class="errormsgbox" >That mobile number has already been registered.</div>';
}
} else {//If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc);//Close the DB Connection
} // End of the main Submit conditional.
You're assigning all of your variables, except $email to $name overwriting each one in succession. This is definitely going to cause strange results which are dependant on the data types of each column in your dataase. If mobileno is set to be an int has a default value of 0 a string or empty value will result in you seeing 0 in your dataase.

foreach invalid argument and undefined variable

I am trying to create a form and i get an error in these lines.
else
{
//report the errors.
echo '<h1> Err... </h1>
<p> The following error(s) have occured</p>';
foreach ($errors as $msg)
{
echo "--$msg<br />\n";
}
echo '</p><p>Please Try Again.</p><p><br/></p>';
}
So, what's wrong?? Here's the error message -
Err...
The following error(s) have occured -
Notice: Undefined variable: errors in
C:\wamp\www\password.php on line 107
Warning: Invalid argument supplied for
foreach() in C:\wamp\www\password.php
on line 107 Please Try Again.
I have set errors as an array.
My code above --
if(isset($_POST['submitted']))
{
require_once('C:\wamp\www\connect.php');
//connecting to db
$errors = array();
if (empty($_POST['email']))
{
$errors[]='Please enter a valid email address.';
}
Here is my complete code -
//forgot password update
include('C:\wamp\www\header.html');
//check if form has been submitted
require_once('C:\wamp\www\connect.php');
//connecting to db
if(isset($_POST['submitted'])) {
$errors = array();
if (empty($_POST['email']))
{
$errors[]='Please enter a valid email address.';
}
else
{
$e = mysqli_real_escape_string($db_name,trim($_POST['email']));
}
//check for current password
if (empty($_POST['password']))
{
$errors[]='Current password does not match.';
}
else
{
$p = mysqli_real_escape_string($db_name,trim($_POST['password']));
}
//check for a new password and match with confirm pass.
if(!empty($_POST['password1']))
{
if($_POST['password1'] != $_POST['cpass'])
{
$errors[] = 'The entered password and confirm password do not match.';
}
else
{
$np=mysqli_real_escape_string($db_name,trim($_POST['password1']));
}
}
if(empty($errors))
//if everything is fine.
//verify the entered email address and password.
$q="SELECT username FROM users WHERE (email='$e' AND password=SHA1('$p'))";
$r=#mysqli_query($db_name,$q);
$num = #mysqli_num_rows($r);
if($num==1)
//if it matches.
//get user id
{
$row=mysqli_fetch_array($r, MYSQLI_NUM);
//udpdate query.
$q="UPDATE users SET password= SHA1('$np') WHERE username=$row[0]";
$r=#mysqli_query($db_name, $q);
if (mysqli_affected_rows($db_name) ==1)
{
echo '<h3>Your password has been updated.</h3>';
}
else {
echo '<h3>Whops! Your password cannot be changed due a system error. Try again later. Sorry</h3>';
echo '<p>' .mysqli_error($db_name). 'Query:' . $q.'</p>';
}
exit();
}
else
{
//invalid email and password
echo 'The email address and password do not match';
}
}
else
{
//report the errors.
echo '<h1> Err... </h1>
<p> The following error(s) have occured</p>';
foreach ($errors as $msg)
{
echo "--$msg<br />\n";
}
echo '</p><p>Please Try Again.</p><p><br/></p>';
}
?>
There is no array named $errors. You will have to look further up your script why not.
You can fix the error message by using
if (!empty($errors) and (is_array($errors)))
foreach ($errors as $msg)
Your foreach loop is out of the scope in regards to where the $error array is defined.
Your code in a nutshell:
if(isset($_POST['submitted'])) {
$errors = array();
} else {
foreach($errors as $error)
}
If $_POST is not set, than your $errors is not defined.
Move your declaration for "$errors = array()" above the line "if(isset($_POST['submitted'])) {
" and everything should work fine!
You have two problems. The first is the cause of the empty/non-existent array and the second is a lack of testing for it.
The first is that you are testing for errors inside of an if block and then looping through them inside of the else block.
if (isset($_POST['submitted'])) {
// create errors array and set errors
} else {
// loop through array of errors
}
So if errors are set, the script doesn't make it to the loop. If the script makes it to the loop, no errors were set.
The second is that you should only enter the foreach loop after you have tested the array:
if (!empty($errors) && is_array($errors)) { // use this line and get rid of the else.
foreach ($errors as $msg) {
echo "--$msg<br />\n";
}
echo '</p><p>Please Try Again.</p><p><br/></p>';
} // and close it.
Basically, what's happening here is you're using $errors before it is defined.
It may be that you need to set "$errors = array( )" near the top of your script so that it is always at least an empty array.

Categories