Registration Form with PHP and MySQL - php

I am learning php and mysql and trying to create a Form with a Registration and Login pages, but I am having trouble getting the registration form to write data to my database. I do not get errors regarding connection to the database, but my tables remain empty when I try to post data. I am getting the error
'Something went wrong while registering. Please try again later.
.
Any help is much appreciated.
<?php
//signup.php
include 'connect.php';
echo '<h2>Register </h2>';
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form method="post" action="">
Username: <input type="text" name="Username" />
Password: <input type="password" name="Password">
Confirm Password: <input type="password" name="Confirm">
<input type="submit" value="Submit" />
</form>';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Save the data
*/
$errors = array(); /* declare the array for later use */
if(isset($_POST['Username']))
{
//the user name exists
//if(!ctype_alnum($_POST['Username']))
if($_POST['Username'] == ['Username'])
{
$errors[] = 'The username is already in use.';
}
}
else
{
$errors[] = 'The username field must not be empty.';
}
if(isset($_POST['Password']))
{
if($_POST['Password'] != $_POST['Confirm'])
{
$errors[] = 'The two passwords did not match.';
}
}
else
{
$errors[] = 'The password field cannot be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly..';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "INSERT INTO
Users(Username, Password)
VALUES('" . mysql_real_escape_string($_POST['Username']) . "',
'" . md5($_POST['Password']) . "',
NOW(),
0)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while registering. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
header ("location: index.htm"); //redirects to Index Page
}
}
}
?>
thank you

Try this. I have added back ticks to the Users table fields
$username = mysql_real_escape_string($_POST['Username']);
$password = md5($_POST['Password']);
$sql= "INSERT INTO Users(`Username`,`Password`) VALUES('$username', '$password')";
You are inserting NOW() and 0. 2 extra values
Note the first step in debugging an SQL query is running it in MySQL first. So try running the SQL statement first in MySQL first with dummy values for Username and Password and see if it works

Related

php check and validate form input with mysql database [duplicate]

This question already has an answer here:
PHP's white screen of death [duplicate]
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
Basically I have this form that asks for email and password.
What I want to do is to compare and check if the inputs match with the data from my table/database.
This is my registration.php (the form)
<form action="Authentication.php" method="post">
<b>Returning Intern Login</b><br/><br/>
Enter your e-mail address: <input type="text" name="email" /><br/><br/>
Enter your password: <input type="password" name="pw2"/><br/><i>(Passwords are case-sensitive and must be 6 characters long)</i><br/><br/>
<input type="reset" value="Reset Login Form" />
<input type="submit" name="submit2" value="Log In" /><hr/><br/>
</form>
and this is the Authentication.php
session_start();
$link = mysqli_connect('localhost','root','');
$database = mysqli_select_db($link,'internship');
$user = $_POST['email'];
$pass = $_POST['pw2'];
// User is logging in
if (isset($_POST["submit2"]))
{
if (empty ($user)) //if username field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique username (email).***</font><br/><br/>";
}
if (empty ($pass)) //if password field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique password.***</font><br/><br/>";
}
}
else
{
$query = "SELECT * FROM Interns WHERE email = '". mysqli_real_escape_string($link,$user) ."' AND password = '". mysqli_real_escape_string($link,$pass) ."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
session_write_close();
It works with the empty inputs.
But when I gave an email and password exactly same from the database/table,
It displays white blank page..
You need to write the entire code within an if statement to ensure the field is filled in, like so:
if (isset($_POST["submit2"]))
{
if (empty ($user)) //if username field is empty echo below statement
{
/* Code */
}
if (empty ($pass)) //if password field is empty echo below statement
{
/* Code */
}
$query = "SELECT * FROM Interns WHERE email = '". mysqli_real_escape_string($link,$user) ."' AND password = '". mysqli_real_escape_string($link,$pass) ."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
else
{
echo "Empty input submit2"; // empty $_POST["submit2"]
}
Hope this helps.
Mysqli takes 4 parameters hostname,username,password, and dbname:
<?php
session_start();
$link = mysqli_connect('localhost','root','','internship');
// User is logging in
if (isset($_POST["submit2"]))
{
$user = $_POST['email'];
$pass = $_POST['pw2'];
if (empty($user)) //if username field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique username (email).***</font><br/><br/>";
}
else if (empty ($pass)) //if password field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique password.***</font><br/><br/>";
}
else
{
$query = "SELECT * FROM Interns WHERE email = '". $user ."' AND password = '".$pass."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
session_write_close();
?>

Getting no result from query

I want to display the first name of the person that logged in to my website. This is the code of my login.php file which is included in one page of my website.
<?php
$connect = mysql_connect("localhost","root","") or die("Error");
mysql_select_db("jpnv_db") or die("Couldn't find db");
function login() {
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT * FROM customers WHERE `username`='$username' AND `password`='$password'");
$names = mysql_query("SELECT contactFirstName FROM customers WHERE `username`='$username'");
if (empty($username)) {
$errors[] = 'Please fill in your username. Click here to try again.';
}
if (empty($password)) {
$errors[] = 'Please fill in your password. Click here to try again.';
}
if ($errors==true) {
foreach ($errors as $error) {
echo $error.'<br />';
}
} else {
if (mysql_num_rows($query)==true) {
echo $names['customers'];
} else {
echo 'Your username and/or password are incorrect. Click here to try again.';
}
}
}
?>
This is the result when the password is incorrect:
This is the result when I actually log in succesfully:
As you can see in my code, it should actually show the name of the person who logged in in the top bar. But however, it is completely empty. What am I doing wrong here?
You never fetch the results from the query and you need to ask for the correct column name from the query:
if (mysql_num_rows($query)==true) {
$name = mysql_fetch_assoc($names)
echo $name['contactFirstName']; // change the column name here
} else {...
You need to prevent SQL Injection or someone will make all of your data disappear.
Please, stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO.
function login() {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) || empty($password))
{
echo "You haven't filled username/password";
// redirect code here//
}
else
{
$query = mysqli_query("$con, SELECT * FROM customers WHERE `username`='$username' AND `password`='$password'");
if ($query && mysqli_num_rows($query)!=0) {
$row =mysqli_fetch_assoc($query);
echo "Customer name is : " . $row['customers']; // you need to specify columns in between ' ' to get it. Change it based on your need.
}
}
}
Note : You should migrate to Mysqli or PDO. $con in the code is the variable that holds db connection.
check this line of code. You are not identifying $name variable.
else {
//$names variable
if $(mysql_num_rows($query)==true) {
$names = mysql_fetch_all($query);
echo $names['customers'];
} else {
echo 'Your username and/or password are incorrect. Click here to try again.';
}
}

I need help converting from mysql_query to PDO

I want to make my site as secure as possible so i need to convert everything i have to PDO. I've successfully done a few things but i ran into a road block on my Sign In page.
Heres my code:
<?php
//signin.php
include 'connect.php';
include 'header.php';
session_start();
echo '<h3>Sign in</h3>';
//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can signout if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<div class="formdivs" id = "logindiv"><form class = "homeforms" method="post" action="">
<label>Username:<input class="forminput" id="smallinput" type="text" name="user_name" /></label>
<label>Password:<input class="forminput" id="smallinput" type="password" name="user_pass"></label>
<input class = "formbutton" type="submit" name = "button" value = "Sign In!"/>
</form></div>';
}
else
{
$errors = array();
if(!isset($_POST['user_name']))
{
$errors[] = 'Missing Username.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'Missing Password.';
}
if(!empty($errors))
{
echo 'Errors';
echo '<ul>';
foreach($errors as $key => $value)
{
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
else
{
//THIS IS WHERE MY PDO PROBLEM BEGINS-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
$password = sha1($_POST['user_pass']);
$sql= "SELECT * FROM users WHERE user_name = :username AND user_pass = :password";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['user_name']);
$stmt->bindParam(':password', $password);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
if(true)
{
if(true)
{
$_SESSION['signed_in'] = true;
while($row = $stmt->fetch())
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
header('Location: /forum.php');
exit;
}
}
}
}
}
include 'footer.php';
?>
My page loads the form but when i press my submit button it turns blank (except for my header and footer) which tells me my php has an error. (obviously)
I want my page to be able to run its error checking (to see if both boxes have input) then to execute upon button press. After i press the button i want it to echo an SQL error if there is one (in situations where the database is down etc) And then also echo if the user name or password does not exist in the database. (IE the select statement returns nothing).
At the moment i have "admin" and "password" just hardcoded in, because i dont think my bindparams statements worked.
EDIT: i should also state that none of my error checking works. If i try to run it with the boxes empty nothing is still shown.
EDIT: SOLUTION: I was using $pdo when i should have been using $DBH. I didnt realize the $pdo variable from the php manual was supposed to be the actual instance i created in my connect.php file. Thanks for your help everybody
You need the colon in your SQL string
$sql= "SELECT * FROM users WHERE user_name = :username AND user_pass = :userpass";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $_POST['user_name']);
$stmt->bindParam(':userpass', $password);
$stmt->execute();
no need for loop , since it's a single record:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
//set your session
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
Keep things simple
if(isset($_POST['submit']){
//form submitted, checking errors
$errors = array();
if(!isset($_POST['user_name']))
{
$errors[] = 'Missing Username.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'Missing Password.';
}
if(!empty($errors))
{
echo 'Errors';
echo '<ul>';
foreach($errors as $key => $value)
{
echo '<li>' . $value . '</li>';
}
echo '</ul>';
exit();//error! let's exit
}else{
//No errors run the PDO query here
}
}else{
//no submission display the form
}

Stop empty values from input boxes from being inserted into my database? PHP

This is the html form (register.php):
<html>
<body>
<form action="handle_registration.php" method="post">
<fieldset><legend>Enter your
information in the form below:</legend>
First Name: <input type="text" name="fname" size="20" maxlength="40"><br>
Last Name: <input type="text" name="lname" size="20" maxlength="40"><br>
Username: <input type="text" name="uname" size="20" maxlength="40"><br>
Password: <input type="text" name="pword" size="20" maxlength="40"><br>
<input type="submit" name="submit" value="submit my info">
</form>
</body>
</html>
This is the php script that handles the registration (handle_registration.php):
<?php
// Create a shorthand for the form data:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$uname = $_POST['uname'];
$pword = $_POST['pword'];
// Create the connection variables:
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "registration_info";
$con = mysqli_connect("$db_host", "$db_user", "$db_pass", "$db_name");
// Check the connection:
if (mysqli_connect_errno ())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Make sure all of the input boxes have a value:
if (empty($fname)) {
die('You forgot to enter your first name!');
}
if (empty($lname)) {
die('You forgot to enter your last name!');
}
if (empty($uname)) {
die('You forgot to choose a username!');
}
if (empty($pword)) {
die('You forgot to choose a password!');
}
// Insert the data from the form into the DB:
$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}
// Close the connection:
mysqli_close($con);
?>
Here's the problem:
I want to submit the entered values into my database if all of the input fields have a value, but when I use the die function after checking to see if they're empty, then it kills the script. I just want to kill the part were it inserts it into my database if one or more of the fields are empty & display an error message that tells which field was empty. I'm not sure how to get around this and any help will be greatly appreciated.
The solution is rather simple. Just store the error message in a variable and before inserting rows into the DB - check weather the error is set or if it's empty. If it's empty - we can insert the row. Otherwise - let's show the error message.
// Currently we do not have an error
$error = NULL;
// Validate
if (empty($pword)) {
$error = 'You forgot to choose a password!';
}
// If there are no errors - lets insert
if (!$error) {
$sql = 'INSERT INTO ...';
}
DOn't use die ,use some variable to store errors and print them later
<?php
// Create a shorthand for the form data:
$fname = $_POST['fname']; $lname = $_POST['lname']; $uname =
$_POST['uname']; $pword = $_POST['pword'];
// Create the connection variables:
$db_host = "localhost"; $db_user = "root"; $db_pass = ""; $db_name =
"registration_info"; $con = mysqli_connect("$db_host", "$db_user",
"$db_pass", "$db_name");
// Check the connection:
if (mysqli_connect_errno ()) { echo "Failed to connect to MySQL: " .
mysqli_connect_error(); }
// Make sure all of the input boxes have a value:
if (empty($fname)) { $error_msg[]='You forgot to enter your first name!'; }
if (empty($lname)) { $error_msg[]='You forgot to enter your last name!'; }
if (empty($uname)) { $error_msg[]='You forgot to choose a username!'; }
if (empty($pword)) { $error_msg[]='You forgot to choose a password!'; }
// Insert the data from the form into the DB:
if(count($error_msg)==0){
$sql = "INSERT INTO basic_information (First_Name, Last_Name,
Username, Password) VALUES ('$_POST[fname]', '$_POST[lname]',
'$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); }
else { echo "Record has been added"; }
// Close the connection:
mysqli_close($con);
}else{
print_r($error_msg);
}
?>
Full working example to stop insertion of empty data
<?php
if (isset($_POST["submit"])) {
$emptyInput = NULL;
if (!($_POST["firstname"] == $emptyInput or $_POST["lastname"] == $emptyInput or $_POST["email"] == $emptyInput)) {
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('" . $_POST["firstname"] . "','" . $_POST["lastname"] . "','" . $_POST["email"] . "')";
if (mysqli_query($conn, $sql)) {
echo 'Record inserted successfully!';
}
} else {
echo 'all fields are compulsory!';
}
}
?>
You could use a $errors variable to hold the errors with all the fields
$error = array();//initializing the $error
if (empty($fname)) {
$error[] = 'You forgot to enter your first name!';
}
if (empty($lname)) {
$error[] = 'You forgot to enter your last name!';
}
if (empty($uname)) {
$error[] = 'You forgot to choose a username!';
}
if (empty($pword)) {
$error[] = 'You forgot to choose a password!';
}
if(!empty($error))//if error occured
{
die(implode('<br />', $error));//Stops the script and prints the errors if any occured
}
// Insert the data from the form into the DB:
$sql = "INSERT INTO basic_information (First_Name, Last_Name, Username, Password)
VALUES
('$_POST[fname]', '$_POST[lname]', '$_POST[uname]', '$_POST[pword]')";
// Enter the info the end user type if everything is ok:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo "Record has been added";
}
// Close the connection:
mysqli_close($con);

change password in mysql table?

Hi im having a problem with my change password script. im trying to allow a user to change their password in the mysql table 'ptb_users.password' it's suppose to store this as md5.
When i hit submit in my form, i'm assuming it goes to changepassword.php but the page is just blank, nothing is echoed and im not getting any errors.
Can someone please show me where im going wrong with this, thanks
Here's my form:
<?php
// CONNECT TO THE DATABASE
require('includes/_config/connection.php');
// LOAD FUNCTIONS
require('includes/functions.php');
// GET IP ADDRESS
$ip_address = $_SERVER['REMOTE_ADDR'];
?>
<?php require_once("includes/sessionframe.php");
require('includes/checks.php');
?>
<?php
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
?>
<?php
//We check if the form has been sent
if(isset($_POST['subject'], $_POST['message_content']))
{
$subject = $_POST['subject'];
$content = $_POST['message_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$subject = stripslashes($subject);
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['subject']!='' and $_POST['message_content']!='')
{
$sql = "INSERT INTO ptb_messages (id, from_user_id, to_user_id, subject, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."', '".$subject."', '".$content."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox2\">The message has successfully been sent.</div>";
}
}
if(!isset($_POST['subject'], $_POST['message_content']))
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
if (empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
}
{
?>
<form method="post" action="includes/changepassword.php" name="form1" id="form1">
<input type="password" name="oldpassword" id="password" class="subject" placeholder="Old Password">
<input type="password" name="oldpassword" id="password" class="message" placeholder="Old Password">
<input type="password" name="newpassword" id="newpassword" class="message" placeholder="New Password">
<input type="image" src="assets/img/icons/loginarrow1.png" name="submit" id="submit" class="submit">
</form>
And here's my mysql function:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
?>
<?php
session_start();
include '_config/connection.php';
$password = $_POST['password'];
$newpassword = $_POST['newpassword'];
$confirmnewpassword = $_POST['confirmnewpassword'];
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']."");
if(!$result)
{
echo "The username you entered does not exist";
}
else
if($password!= mysql_result($result, 0))
{
echo "";
}
if($newpassword=$confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm new password fields must be the same";
}
?>
if(isset($_POST['submit']))
{
$email = $_POST['email'];
echo $newpassword = ($_POST['password1']);
echo $confirmpasssword = ($_POST['password2']);
if($newpassword=$confirmpassword)
{
echo $newpassword = md5($newpassword);
echo $result = mysql_query("UPDATE users SET password='$newpassword' WHERE email='$email' ");
}
if($result)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm password fields must be the same";
}
}
can anyone tell me is this correct coding, to change password and store in mysqldb.
first you do not check the old password properly (md5 stored, plaintext compare... won't work)
second you do not have any confirmpassword set, so this wont work too
what would work is:
$password = md5($_POST['password']);
$newpassword = md5($_POST['newpassword']);
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']." AND password = '".$password."'");
if(!$result)
{
echo "The username you entered does not exist or old password didn't match";
}
else
{
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
There are many things wrong with this.
Let's get the basics out of the way first:
Don't use mysql_ functions. switch to PDO or mysqli while you can.
md5 is in its dying days. See this answer - understandably, you may be so entrenched in md5 you can't get out without pestering every user to update their pw.
Your problem then is this:
if($password!= mysql_result($result, 0))
You're not comparing against a md5 stored hash. It should be something like this:
if(md5($password) != mysql_result($result, 0))
and this:
if($newpassword=$confirmnewpassword)
is just reassigning a variable. I think you wanted
if($newpassword == $confirmnewpassword)
As for output, you may want to consider the if/else structures you're using here. This could be cleaned up significantly and all together looks out of date. Maybe just an opinion.
If you have a specific thing to hone in on, let me know and I may update.
EDIT
This whole block should be cleaned. Something like this may help:
if(!$result)
{
echo "The username you entered does not exist";
}
else
{
if(md5($password) != mysql_result($result, 0))
{
echo "Current PW does not match what we have";
}
else
{
if($newpassword == $confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."") or die(mysql_error());
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
}
else
{
echo "The new password and confirm new password fields must be the same";
}
}
}

Categories