Undefined index in registration form PHP - php

I trying to create a simple user registration, that saves data into a database.
But I have an error I cant defeat.
Its says
Notice: Undefined index: pass_conf in C:\wamp\www\book\reg.php on
line 27
But my pass_config seems to be right.
Any ideas whats the problem ? this is the php code
/// Updating my code, this one works
<?php
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "pagination";
$connection = mysql_connect($host,$dbuser,$dbpass);
$db = mysql_select_db($dbname,$connection);
/*
$name = $_POST["username"];
$pass = $_POST["password"];
$pass_conf = $_POST["pass_conf"];
$email = $_POST["email"];
$ip = $_POST["ip"]; */
$name = isset($_POST['username']) ? $_POST['username'] : 0;
$pass = isset($_POST['password']) ? $_POST['password'] : 0;
$pass_conf = isset($_POST["pass_conf"]) ? $_POST["pass_conf"] : 0; // 0 equals your default off value.
$email = isset($_POST['email']) ? $_POST['email'] : 0;
$ip = isset($_POST['ip']) ? $_POST['ip'] : 0;
if($name == false || $pass == false || $pass_conf == false || $email == false){
echo "Please fill in all the required fields.";
};
if($pass != $pass_conf){
echo "Passwords do not match.";
}else {
$connection = mysql_connect($host,$dbuser,$dbpass);
$db = mysql_select_db($dbname,$connection);
$sql = "INSERT INTO user (username,password,email,ip) VALUES ($name, $pass, $email, $ip)";
$result = mysql_query($sql);
echo "Thank you for your registration to Our Site";
};
?>
I Will add my form.php also since I got a request for it.
<?php
$IP = $_SERVER['REMOTE_ADDR'];
?>
<form name=reg action=reg.php method=post>
Username : <input type=text name=username><br>
Password : <input type=password name=password><br>
Confirm :<input type=password name=pass_conf><br>
Email : <input type=text name=email><br>
<input type=hidden name=ip value='<?php echo $IP ?>'>
<input type=submit value='Register'>
</form>
Thanks

instead of $x = $_POST['x'] use $x = isset($_POST['x']) ? $_POST['x'], null.
Or use:
function post($key, $default = null) {
return isset($_POST[$key]) ? $_POST[$key] : $default;
}

First off, good job on using E_ALL while creating your app! Your "pass_conf" value is probably a checkbox that isn't selected when submitting your form and so no value is ever sent. A simple:
$pass_conf = isset($_POST["pass_conf"]) ? $_POST["pass_conf"] : 0; // 0 equals your default off value.

That message means that the value you are trying to get is not present in the array. So either the value is not filled in or is not passed thru correctly (check the fields name, it has to be exactly the same).

Have you tried:
if (array_key_exists("pass_conf", $_POST))
$pass_conf = mysql_real_escape_string($_POST["pass_conf"]);
else
$pass_conf = null;
$sql =
"INSERT INTO events (username, password, email, ip) " .
"VALUES ('{$name}','{$pass}','{$email}','{$ip}')";
See this question that I asked for my full example and scroll down to how it was answered by user dldnh; it's similar to yours, so maybe it will help you: [link] Undefined index notice

Related

How do I send POST data to another session in PHP?

I have a session that accepts login information and if user is valid within my database, I am setting the pages post array with the other data for user and displaying it in another session on a different page. My email and password are getting sent to the next session but the rest of my data isn't and I cant figure out why. I do know that I am successfully retrieving the data of the login user from the database table, however there is some issue with the other fields being sent to post and then on to the next session.
My login page
<?php
session_start();
if(isset($_POST["firstName"]))
{
$_SESSION["firstName"] = $_POST["firstName"];
}
if(isset($_POST["lastName"]))
{
$_SESSION["lastName"] = $_POST["lastName"];
}
if(isset($_POST["phone"]))
{
$_SESSION["phone"] = $_POST["phone"];
}
if(isset($_POST["email"]))
{
$_SESSION["email"] = $_POST["email"];
}
if(isset($_POST["sin"]))
{
$_SESSION["sin"] = $_POST["sin"];
}
if(isset($_POST["password"]))
{
$_SESSION["password"] = $_POST["password"];
header('Location: ViewAllEmployees.php');
exit;
}
require "MySQLConnectionInfo.php";
$error = "";
// if email and password not set
if (! isset($_POST["email"]) || ! isset($_POST["password"])) {
$error = "Please enter employee login information.";
} else {
// if email and password set from login input
if ($_POST["email"] != "" && $_POST["password"] != "") {
try {
$pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully" . "</br>";
$sqlQuery = "SELECT * FROM employee";
try {
$result = $pdo->query($sqlQuery);
$rowCount = $result->rowCount();
if ($rowCount == 0)
echo "There are no rows to display from the Employee table ";
// find employee
for ($i = 0; $i < $rowCount; $i++) {
$row = $result->fetch();
$firstname = $row[1];
$lastname = $row[2];
$email = $row[3];
$phone = $row[4];
$sin = $row[5];
$password = $row[6];
if (isset($_POST["email"]) && isset($_POST["password"])) {
if ($email == $_POST["email"] && $password == $_POST["password"]) {
$_POST["firstName"] = $firstname;
$_POST["lastName"] = $lastname;
$_POST["email"] = $email;
$_POST["phone"] = $phone;
$_POST["sin"] = $sin;
$_POST["password"] = $password;
break;
}
}
}
} catch (PDOException $e) {
echo "Login unsuccessful. " . $e->getMessage();
}
$pdo = null;
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
} else
$error = "Please enter employee login information.";
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
include "Header.php";
include "Menu.php";
?>
<div class="content">
<form action="Login.php" method="post">
Email Address: <input type="text" name="email" /> <br /> Password: <input
type="text" name="password" /> <br /> <br /> <input type="submit"
value="Login" />
</form>
<br /> <br />
</div>
<?php
echo $error;
include "Footer.php";
?>
</body>
</html>
The problem here is, you set the $_SESSION array before you assigning them to the $_POST array. The moment you assign the $_SESSION['firstName'] = $_POST['firstName'], the $_POST['firstName'] is empty.
Solution : Move the area where you set the $_SESSION variable
if(isset($_POST["firstName"]))
{
$_SESSION["firstName"] = $_POST["firstName"];
}
after you setting the $_POST variable.
if ($email == $_POST["email"] && $password == $_POST["password"]) {
$_POST["firstName"] = $firstname;
$_POST["lastName"] = $lastname;
For the email and the password, these fields get saved in the session because you're passing these two POST fields from the HTML Form and in the top section where you set the $_SESSION variable, these two fields are already populated in the $_POST array.
There are some parts of the code that could be improved, like:
Add the email directly here in a WHERE clause, so that you don't need to do a for loop for all the employees.
$sqlQuery = "SELECT * FROM employee";
if (isset($_POST["email"]) && isset($_POST["password"])) in the try block is not necessary and could be moved up and replace the first check (where you are using != "").
Regardless, to answer your question you need to know a bit of how the flow of the code is. The reason the other information isn't being sent to other page is that where you are setting the $_SESSION variable, that information isn't available to the code.
You have a form in your html that sends data to your code. This will only populate $POST["email"] and $POST["password"]. In the beginning of the code you are checking for other data in $POST which aren't yet populated therefore they won't be saved in $_SESSION.
If you insist to not using Kinglish's approach from the comments, you should move $_SESSION["phone"] = $_POST["phone"], etc to where you have found the user from the database.

String data conversion: Inserting data from Spinner using mysql

I am trying to add data into MySQL database through spinner that has several options to choose. I do not know how to state value from spinner into MySQL code. The error occurs on the 39th line, which first line of Inserting Into database using MySQL code. I look forward to hearing from you soon.
<?php
include 'db.php';
$user_type = ['user_type'];
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$phone = $_POST['phone'];
if(/*$user_type == '' ||*/ $first == '' || $last == '' || $email == '' || $username == '' || $password == '' || $phone == '')
{
echo 'Please, fill all fields';
} else{
$sql = "SELECT * FROM users WHERE user_username='$username'";
$check = mysqli_fetch_array(mysqli_query($conn,$sql));
if(isset($check))
{
echo 'Username already exist. Please, use another one.';
}else{
$hashedPWD = password_hash($password , PASSWORD_DEFAULT); //hash password
$sql = "INSERT INTO users (user_type, user_first, user_last, user_email, user_username, user_pwd, user_phonenumber) VALUES('$user_type','$first','$last','$email','$username','$hashedPWD','$phone')";
if(mysqli_query($conn,$sql))
{
echo 'Successfully registered';
} else{
echo 'Oops! Please try again!';
}
}
mysqli_close($conn);
}

i am getting errors im running on PHP

$submit = $_POST['submit'];
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatpassword = strip_tags($_POST['confirmpassword']);
$date = date ("Y-m-d");
i get **"Notice: Undefined index"**
but when i do this
if(isset($_POST['submit']))
{
$submit = $_POST['submit'];
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$repeatpassword = strip_tags($_POST['confirmpassword']);
$date = date ("Y-m-d");
}
the undefined index gets fixed but Notice: Undefined variable: submit is my new error why is that???
It's notice because you want to use variable which is not set you can fix it by checking it with isset() function
$submit = null;
if(isset($_POST['submit'])
$submit = $_POST['submit'];
or with short syntax
$submit = isset($_POST['submit']) ? $_POST['submit'] : null;
same applies to other variables passed via $_POST
Try with
$submit = isset ( $_POST ['submit'] ) ? $_POST ['submit'] : null ;
Change:
if(isset($_POST['submit']))
In:
if(isset($_POST) && isset($_POST['submit']))
This is due to no value for 'submit' being passed by POST.
Check if $_POST['submit'] is empty prior to assigning its value to a variable.
Do You have in your form
<input type = 'submit' name = 'submit' />
if you have placed only
<input type = 'submit' />
It will not work
Changed it to start with this
<?php
if(isset($_POST['submit']) != "")
{
$submit = $_POST['submit'];
......
}
?>

PHP Login Database Issues

I am new to PHP so please be patient with me! I am trying to set up a user login page but every time I click log in it won't recognize the data that is already in the database. I currently have 7 sections in a the table but only taking data from 2 sections. I am unsure where abouts I am going wrong could be the php or the MySQL queries Would someone help me please!
<?PHP
$email = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = $_POST['Email'];
$pword = $_POST['Password'];
$email = htmlspecialchars($email);
$pword = htmlspecialchars($pword);
$e_mail = "root";
$pass_word = "";
$database = "the_travel_cult";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $e_mail, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$email = quote_smart($email, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM user_login WHERE Email='$email' AND Password='$pword'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
//if(!$result) die ('Unable to run query:'.mysql_error());
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['user_login'] = "1";
header ("Location: SignedIn.php");
}
else {
session_start();
$_SESSION['user_login'] = "";
//$errorMessage = "Not Registered";
header ("Location: Register.php");
}
}
else {
$errorMessage = "Error logging on";
}
mysql_close($db_handle);
}
else {
$errorMessage = "Error logging on";
}
}
?>
<FORM NAME ="form1" METHOD ="POST" ACTION ="HomePage.php">
<form method=post action=”login.php”>
<p><center><strong>Email Addres:</strong></center><br>
<center><input type=”text” name= 'email' value="<?PHP print $email;?>" size=40 maxlength=100></center>
<p><center><strong>Password</strong></center><br>
<center><input type=”text” name= 'password' value="<?PHP print $pword;?>" size=40 maxlength=20></center>
<P align = center>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
<form action="Register.php"> <input type="submit" value="Sign Up"> </form>
First off, congratulations on starting to code. I hope you're having fun!
It looks like you might have a case of "case sensitivity" going on. I noticed that you have the following code at the top:
$email = $_POST['Email'];
$pword = $_POST['Password'];
However, in your HTML, you're actually passing those variables named in all lowercase. Try changing either the code at the top to:
$email = $_POST['email'];
$pword = $_POST['password'];
Or the name of your inputs to "Email" and "Password" (again, notice the uppercase first letter). An easy way to check if the problem is here (vs something in the query) is to
var_dump($_POST);
to see what exactly your script is getting from the form submission.
For more information, see PHP's http://php.net/manual/en/language.variables.basics.php or check out a related post to see how you can make your own case insensitivity check though be warned: it's more work. PHP: Case-insensitive parameters

PHP/MySQL - Update Database/Run PHP Script on Button Click

I have a 'registration' page in PHP and I would like the script to run when an HTML button is clicked.
The PHP basically checks if all fields are filled, checks if the password and email confirmations are the same and saves to the database.
This is the code:
<?php
$Name = isset($_POST['Name']);
$Surname = isset($_POST['Surname']);
$Username = isset($_POST['Username']);
$Email = isset($_POST['Email']);
$C_Email = isset($_POST['C_Email']);
$Password = isset($_POST['password']);
$C_Password = isset($_POST['c_password']);
$SecQ = isset($_POST['SecQ']);
$SecA = isset($_POST['SecA']);
$con = mysql_connect('localhost', 'admin', 'storefile1234');
mysql_select_db ("storefile");
$check_username = mysql_query("SELECT FROM users WHERE username = '$Username'");
$check_email = mysql_query("SELECT FROM users WHERE Email = '$Email'");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if ($Name == null || $Surname== null || $Username == null || $Password == null || $C_Password == null || $Email == null || $C_Email == null || $SecQ == null || $SecA == null ) {
echo "Missing details. Please enter all fields.";
} else {
if(mysql_num_rows($check_username) != 0 && mysql_num_rows($check_email) != 0)
{
echo "Username/Email already exists";
}
if ($Email == $C_Email && $Password == $C_Password) {
$query = "INSERT INTO users (Username, Name,Surname, Password, Email, SecQ, SecA) VALUES ('NULL', ".$Username."', ".$Name."', ".$Surname."', ".$Password."', ".$SecQ."', ".$SecA."', ".$Email.')"';
mysql_query($query) or die ('Error registering.');
echo "Greetings, ".$Name.", you have been registered. ";
} else {
echo "Error registering your account. Please try again.";
}
}
?>
Also, is it recommended?
Whenever I run this page Missing details. Please enter all fields. displays, without having entered any details.
How do you do this?
You tying to get values by isset($_POST['Username']); and like this functions...
But documentation says: Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
So check on true, nut null. And escape your POST data after.
You can do like this:
$Name = isset($_POST['Name']) ? mysql_real_escape_string($_POST['Name']) : null;
P.S. Please again. Do not use mysql_* function. They are DEPRECATED.
Look on PDO (or mysqli_*)
For the issue of printing that message when you first load the page, use the array_key_exists function to test if the user has already submited something before checking if any field is null. Something like this:
if (array_key_exists('Name', $_POST) || array_key_exists('Surname', $_POST) || ... )
if ($Name == null || $Surname== null || ... )
echo "Missing details. Please enter all fields.";
Observation: you cannot use the isset function for the same purpose since, according to php documentation, it "determine if a variable is set and is not NULL"
You misuse isset
Try something like this:
$Name = null;
if (isset($_POST['Name'])) {
$Name = $_POST['Name'];
}
isset is only to check if a value is set.

Categories