I have a registration form and I want it to connect to my database. I used phpmyadmin as my database. The code that I used to connect the two is below:
db.php
<?php
$hostname = "127.0.0.1";
$user = 'root';
$password = '';
$db = 'dbTest';
//connection to db
$conn = mysqli_connect("$hostname", "$user", "$password", "$db")or die(mysqli_error());
mysqli_select_db($conn, "peanat")or die(mysqli_error());
$username = $_POST['username'];
$password = $_POST['password'];
$username = strtolower(trim($_POST["username"]));
$username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
$checkUsername = mysqli_query($conn, "Select username * FROM users WHERE Username='$username'");
$numrows = mysqli_num_rows($checkUsername);
if($numrows!==1) {
echo "Username not available";
}else{
$sql = "INSERT INTO `users` (`Username`, `Password`) VALUES ('$username', '$password')";
if(!mysqli_query($conn, $sql)) {
die(mysqli_error());
} else {
echo "1 record added";
}
}
?>
this is my reg form
<form id="register" action="db.php" method="post" >
<div class="col-4">
<label>
Username
<input placeholder="" id="username" name="username">
</label>
</div>
<div class="col-4">
<label>Password
<input type="password" placeholder="" id="password" name="password">
</label>
</div>
<div class="col-4">
<label>Confirm Password
<input type="password" placeholder="" id="password2" name="password2">
</label>
</div>
<div class="col-submit">
<input type="submit" class="submitbtn" name="register" value="Register">
</div>
</form>
now the problem I'm encountering is, every time I click the register button, it just goes to the designated page and it shows the code of that page. where do you think is my error...
Place the two files (db.php & reg.HTML) into your local web server folder. (eg. C:/xampp/htdocs/form/
Open any internet browser and type in the path to your HTML file. Eg. Local host/form/reg.html and hit enter.
You should get HTML form displayed on the browser and you're done.
Related
I've created 2 webpages for administrator register and login. After registration of the admin at registrationadmin.php page, it says the registration was successfully done. Once going to login webpage and entering correct credentials, it notifies me that username/password are incorrect. When I check with my database, details of admin registration are stored in the database of the admin table.
What is the problem/how can I resolve this?
Loginadmin code:
<?php
require('db.php');
session_start();
if (isset($_POST['admin_username'])){
$admin_username = stripslashes($_REQUEST['admin_username']);
$admin_username = mysqli_real_escape_string($con,$admin_username);
$admin_password = stripslashes($_REQUEST['admin_password']);
$admin_password = mysqli_real_escape_string($con,$admin_password);
$admin_password = md5($admin_password);
$query = "SELECT * FROM `admin` WHERE admin_username='$admin_username' and admin_password='".md5($admin_password)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['admin_username'] = $admin_username;
header("Location: adminindex.php");
}else{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='loginadmin.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h3>Admin Log In</h3>
<form action="" method="post" name="login">
<input type="text" name="admin_username" placeholder="User Name" required />
<input type="password" name="admin_password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
Back to main page
</div>
<?php } ?>
Registrationadmin.php code:
<?php
require('db.php');
if (isset($_REQUEST['admin_username'])){
$admin_username = stripslashes($_REQUEST['admin_username']); // removes backslashes
$admin_username = mysqli_real_escape_string($con,$admin_username); //escapes special characters in a string
$admin_email = stripslashes($_REQUEST['admin_email']);
$admin_email = mysqli_real_escape_string($con,$admin_email);
$admin_password = stripslashes($_REQUEST['admin_password']);
$admin_password = mysqli_real_escape_string($con,$admin_password);
$query = "INSERT into `admin` (admin_username, admin_email, admin_password) VALUES ('$admin_username', '$admin_email','".md5($admin_password)."')";
$result = mysqli_query($con,$query);
if($result){
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='loginindex.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h2>REGISTER AS ADMIN </h2>
<form name="registration" action="" method="post">
<input type="text" name="admin_username" placeholder="Username" required />
<input type="email" name="admin_email" placeholder="Email" required />
<input type="password" name="admin_password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
</div>
<?php } ?>
Check your insert query (I split it to 2 rows for better readability):
$query = "INSERT into `admin` (admin_username, admin_email, admin_password)
VALUES ('$admin_username', '$admin_email','".md5($admin_password)."')";
Instead of using values stored in variables $admin_username and $admin_email, you are entering just string $admin_username and $admin_email.
You must fix in same way as the password:
$query = "INSERT into `admin` (admin_username, admin_email, admin_password)
VALUES ('".$admin_username."', '".$admin_email."','".md5($admin_password)."')";
I am learning MySQL and PHP and I trying to build a simple login webpage and connect with MySQL.
I have built the page with HTML and CSS, also I downloaded PHP and installed MySQL, I am getting confused about how to combine those things and when I input my password and username it will go to successful page.
I am not seeking an answer but need some suggestions for the next step.
PLEASE NOTE - the way my SQL queries are written here are open to SQL injection (see here to get the changes you would need to make)
So to start. You want to create a database table to store your users, a form to create users, and some code to query the data into the database.
i would start with a form like this:
<form method="post" class="mt-3">
<input type="hidden" name="do" value="create" />
<div class="form-group">
<label for="itemName">First Name</label>
<input type="text" class="form-control" name="firstName">
</div>
<div class="form-group">
<label for="serialNumber">Last Name</label>
<input type="text" class="form-control" name="lastName">
</div>
<div class="form-group">
<label for="serialNumber">Username</label>
<input type="text" class="form-control" name="userName">
</div>
<div class="form-group">
<label for="serialNumber">Password</label>
<input type="password" class="form-control" name="passWord">
</div>
<a id="create-member" class="btn btn-success text-white">Submit</a>
</form>
then you want some code that will take the values you have in that form and turn them into a query to add that info into your table.
if(isset($_POST['do'])) && $_POST['do'] == 'create'
{
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$username = $_POST['userName'];
$password = password_hash($_POST['passWord'], PASSWORD_BCRYPT);
$sql = "INSERT INTO members (first_name, last_name, username, password) VALUES ('".$firstName."', '".$lastName."', '".$username."', '".$password."')";
mysqli_query($conn, $sql); //$conn is set in my header file and included into every page.
}
That is pretty much the process for creating a user and adding it to your table, obviously you'll have to break it down and change values to what you have in your table etc.
Next it's the case of verifying a login.
first, a login form:
<form method="post">
<input type="hidden" name="do" value="login" />
<div class="form-group">
<label for="usename">Username</label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
and then an authentication query to follow, this will take the info in the login page, hash the password you entered and then compare it with the one in your database.
if (isset($_POST['do']) && $_POST['do'] == 'login')
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT id, first_name, last_name, password FROM members WHERE username= '$username'";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if($query->num_rows == 0)
{
echo "Username or password incorrect";
}else{
$data = mysqli_fetch_array($query);
if(!password_verify($password, $data['password']))
{
echo "Username or password incorrect";
}else{
session_regenerate_id();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['member_id'] = $data['id'];
$_SESSION['first_name'] = $data['first_name'];
$_SESSION['last_name'] = $data['last_name'];
}
}
}
}
?>
don't be scared about the $_SESSION variables at the bottom, i just set all user data as that so it's easier to access it on other pages, then i just follow with a header to my index.php page. In my header i also check to see that $_SESSION['loggedin'] is set to true and if not it redirects them to the login page (also be care to take into account the user might be on the login page, you dont want a redirect error)
This is my first detailed answer on this site so i hope it helps you :)
hi guys please l need some help. lm setting up a user registration sign up form. but l was NOT ABLE TO INSERT THE USER INFO IN TO THE DATABASE. And the code did not display any error message, meaning that everything is fine.
But when l tried to sign up it gives the form's error message "Failed to Register User".
this is the code: (and check at the bottom the connect.php code)
<?php
require_once('connect.php');
//print_r($_POST);
if(isset($_POST) & !empty($_POST)) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// storing the sign up info in to the database
$sql = "INSERT INTO usermanagement (username, email, password) VALUES ('$username', '$email', '$password')";
//executing the query
$result = mysqli_query($connection, $sql);
if($result){
echo "User Registered Successfully";
}
else{
echo "Failed to Register User";
}
}
?>
<div id="form-signup">
<form id="signup-form" name="sign-up" action="sign.php" method="POST">
<h1>Create your profile</h1>
<p>
<input type="text" name="username" id="username" class="signup-input" required="required" placeholder="Full name*" >
</p>
<p>
<input type="email" name="email" class="signup-input" required="required" placeholder="Email*" >
</p>
<p>
<input type="password" name="password" class="signup-input" required="required" placeholder="Mot de passe*">
</p>
<!-- <p>
<input type="password" name="confirmpassword" class="signup-input" required="required" placeholder="Confirmez mot de passe*">
</p> -->
<p class="agree"> By signing up, you agree to Tout-Passe's <br> Terms of use<br> and Privacy Policy.
</p>
<p>
<input type="submit" class="signup-btn" name="btn-signup" value="Create Account">
</p>
<p class="already">Already on Tout-Passe? Log in</p>
</div><!--END OF PHASE-1-->
</form> <!--END OF SIGN-UP-->
</div><!--END FO ALLFORM-->
CONNECT CODE
<?php
$connection = mysqli_connect('localhost', 'root', '');
if(!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'listing');//listing = database
if(!$select_db){
die("Failed to select database" . mysqli_error($connection));
}
?>
You did a mistake line 4, if(isset($_POST) & !empty($_POST)) { you have only one & you should have two like this: if(isset($_POST) && !empty($_POST)) {
Beside this, when your message tell you that it failed to register the user, it does not explain why, to solve this you have to add a mysqli_error() like this:
require_once('connect.php');
//print_r($_POST);
if(isset($_POST) && !empty($_POST)) {
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// storing the sign up info in to the database
$sql = "INSERT INTO usermanagement (username, email, password) VALUES ('$username', '$email', '$password')";
//executing the query
$result = mysqli_query($connection, $sql);
if($result){
echo "User Registered Successfully";
}
else{
echo "Failed to Register User, reason: " . mysqli_error($connection);
}
}
Also there is two problems with your code:
It is faillibe to SQL injection. What is SQL injection?
You should test each of your global variables are set individually like this: if(isset($_POST['username']) && !empty($_POST['username'])) and not like this: if(isset($_POST) && !empty($_POST))
I have 2 problems.
Basic story: I have created a SIMPLE registration and login system.
Problem1: If I try to register a new account then it says "user registration failed". At the moment it should say that because mysql can't get right information from forms. But problem is that I don't know why. Everything seems correct...
Problem2: If I try to login with existent account then it seems that browser is only refreshing the page and nothing else...
Registration with php code:
<?php
require ('insert.php');
// If values posted, insert into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$name = $_POST['name'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
// nimi refers to name, it's correct
$query = "INSERT INTO `user` (nimi, email, username, password)
VALUES('$name', '$email', '$username', '$password')";
//POST retrieves the data.
$result = mysqli_query($connection, $query);
if($result){
$smsg = "User Created Successfully.";
} else {
$fmsg = "User Registration Failed";
}
}
mysqli_close($connection);
?>
<html>
...
<body>
...
<div>
<form method="POST" class="form-horizontal" role="form">
<!-- Status, how registering went -->
<?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
<?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
<!-- Registration form starts -->
<h2>Form</h2><br>
<label for="Name"></label>
<input name="name" type="text" id="name" maxlength="40" placeholder="Ees- ja perenimi" class="form-control" autofocus> <!-- lopp -->
<label for="email"></label>
<input name="email" type="email" id="email" maxlength="65" placeholder="Email" class="form-control"> <!-- lopp -->
<label for="Username"></label>
<input name="username" type="text" id="userName" maxlength="12" placeholder="Kasutajatunnus/kasutajanimi" class="form-control" required> <!-- lopp -->
<label for="Password"></label>
<input name="password" type="password" id="password" maxlength="12" placeholder="Parool" class="form-control" required>
<button type="submit" class="btn btn-primary btn-block">Join</button>
</form> <!-- /form -->
</div> <!-- ./container -->
...
</body>
</html>
Login:
<?php
session_start();
require ('insert.php');
//Is username and password typed?
if (isset($_POST['username']) and isset($_POST['password'])){
//Making vars from inputs
$username = $_POST['username'];
$password = $_POST['password'];
//Checking existent of values.
$query = "SELECT * FROM `liikmed`
WHERE username='$username'
and password='$password'";
$result = mysqli_query($connection, $query)
or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
//3.1.2 If values equal, create session.
if ($count == 1){
$_SESSION['username'] = $username;
} else {
//If credentials doesn't match.
$fmsg = "Invalid Login Credentials.";
}
}
//if user logged in, welcome with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hai " . $username . "";
echo "This is the Members Area";
echo "<a href='logout.php'>Logout</a>";
}else{}
?>
<html>
...
<body>
...
<div id="bg"></div>
<form method="POST" class="form-horizontal">
<h2>Login</h2><br>
<label for="User"></label>
<input name="username" type="text" maxlength="15" placeholder="Username" class="form-control" required autofocus>
<label for="Password"></label>
<input name="password" type="password" maxlength="50" placeholder="Password" class="form-control" required autofocus>
<button type="submit" class="btn btn-primary btn-block">Enter</button>
</form>
</div>
...
</body>
</html>
And finally php database connection file (called insert.php):
<?php
$connection=mysqli_connect("localhost","root","pw");
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'my_database');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
First of all in your login PHP code, you only started a session but you didn't tell the from where to direct to if login is successful. Add a header to the code. That is;
if ($count == 1){
$_SESSION['username'] = $username;
header("Location: page.php"); //the page you want it to go to
}
And your registration PHP code looks ok. Check your database table if you've misspelt anything there.
Your logic to set the $_SESSION['username'] requires that the username and password combination exists once in your database.
This might sound silly but can you confirm that this is the case (i.e. confirm that you have not created the same username and password combination).
Altering the logic to be > 1 would also get around this temporarily. So your code
if ($count == 1){
$_SESSION['username'] = $username;
}
should become
if ($count > 1){
$_SESSION['username'] = $username;
}
I have been trying to create a greeting after a user logs in that says "Welcome, first name (dynamic)." so when the user logs in they are greeted with their name. For some reasont it has not been working out. I am new at php so this may be a simple error. Any assist or advice would be useful. Thanks.
main code
session_start();
$mysql_hostname = 'localhost';
$mysql_user = 'username';
$mysql_password = 'password';
$mysql_database = 'db_users2015';
$connect = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die ("Couldn't connect");
echo "<BR>Connection Successful";
//to put data into database
//select database
$db_selected= mysql_select_db($mysql_database, $connect)
or die ("Couldn't connect to the database");
//frontend and backend data processing
$email= $_POST['email'];
$password= $_POST['password'];
//To see if email is registered
$sql = "SELECT COUNT(*) FROM users WHERE email= '{$_POST['email']}'";
$sql_result = mysql_query($sql);
if (mysql_result($sql_result, 0)<1)
{
die("<BR>Email address not found");
}
else{
echo "Login Successful!";
}
//To check if email and password match
$sql = "SELECT count(*) FROM users WHERE email = '$email' AND
password ='$password' LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
$firstname = $_SESSION['firstname'];
$_SESSION['firstname']= $_POST['firstname'];
if (mysql_result($result, 0) > 0){
echo "<BR>Login Successful, welcome";
echo $_SESSION['firstname'];
}
if (mysql_result($result, 0) < 1){
echo 'wrong password/username combo';
}
?>
<HTML>
<HEAD>
<TITLE> Programming</TITLE>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<LINK REL="stylesheet" TYPE="text/css" href="homework2.css">
</HEAD>
<BODY>
<!-- CSS for http://the7.dream-demo.com/ -->
<div id="container">
<div id="header">
<div class="menuitem"> Home </div>
<div class="menuitem">Products</div>
<div class="menuitem">Case Studies</div>
<div class="menuitem">Pricing</div>
<div class="menuitem">About Us</div>
</div>
<div id="bodycontent">
<div id="banner">
<div id="bannerleft"> <h1> We make you better athletes. Find out how! </h1> </div>
<div id="signin">
<form class="well form-inline" action="login.php" method="post">
<input type="text" class="input-small" placeholder="Email" name="email" >
<input type="password" class="input-small" placeholder="Password" name="password">
<br><br>
<!--
If you do not want to use twitter bootstrap css then you should uncomment next 6 lines and uncomment the
above 2 lines that provide input boxes
<label for="email">Email:</label>
<input type="text" name="email" id="email">
<br>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
<br>
-->
<input type="submit" name="submit" id="logmein" value="Log In">
</form>
</div>
</div>
<div id="featurestrip">
<div id="signup">
<form action="signup.php" method="post">
<label for="firstname">Firstname:</label>
<input type="text" name="signup-firstname" id="signup-firstname">
<br>
<label for="lastname">Lastname:</label>
<input type="text" name="signup-lastname" id="signup-lastname">
<br>
<label for="email">Email: </label>
<input type="text" name="signup-email" id="signup-email">
<br>
<label for="password">Password:</label>
<input type="password" name="signup-password" id="signup-password">
<br>
<label for="password">Reconfirm Password:</label>
<input type="password" name="signup-repassword" id="signup-repassword">
<br><br>
<input type="submit" name="signmeup" id="signmeup" value="Sign Me Up!">
</form>
</div>
<div id="featureright"> <p>Sign up and find out more on how we can help. Pricing starts at $19.95 a month. </p>
<p><h3>Premium service starts at $49.95.</h3></p>
</div>
</div>
<div id="corefeatures">
<img height="200px" src="http://www.hockeymanitoba.ca/wp-content/uploads/2013/02/ltad-model.jpg">
</div>
<div id="testimonials"> Testimonial
<img height="200px" src="http://www.neuroexplosion.com/storage/development%20model%20jpeg.jpg?__SQUARESPACE_CACHEVERSION=1305662626397">
<img height="200px" src="http://www.phecanada.ca/sites/default/files/physical_literacy/LTAD_FMS.jpg">
</div>
<!--
<div id="portfolio"> Portfolio</div>
<div id="skills"> Skills</div>
-->
</div>
<div id="footer">Copyright Notice. All Rights Reserved. 2014</div>
</div>
</BODY>
</HTML>
2nd php code edit
<?php
session_start();
$mysql_hostname = 'localhost';
$mysql_user = 'username';
$mysql_password = 'password';
$mysql_database = 'db_users2015';
$connect = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die ("Couldn't connect");
echo "<BR>Connection Successful";
//to put data into database
//select database
$db_selected= mysql_select_db($mysql_database, $connect)
or die ("Couldn't connect to the database");
//frontend and backend data processing
$email= $_POST['email'];
$password= $_POST['password'];
//To see if email is registered
$sql = "SELECT COUNT(*) FROM users WHERE email= '{$_POST['email']}'";
$sql_result = mysql_query($sql);
if (mysql_result($sql_result, 0)<1)
{
die("<BR>Email address not found");
}
else{
echo "Login Successful!";
}
//To check if email and password match
$sql = "SELECT(*) FROM users WHERE email = '$email' AND
password ='$password' LIMIT 1";
$userdata = mysql_fetch_assoc($result);
$result = mysql_query($sql) or die(mysql_error());
$firstname = $_POST['firstname'];
$_SESSION['firstname]' = $userdata['firstname'];
if (mysql_result($result, 0) > 0){
echo "<BR>Login Successful, welcome";
echo $firstname;
}
if (mysql_result($result, 0) < 1){
echo 'wrong password/username combo';
}
?>
under //To check if email and password match
put this:
$result = mysql_query("SELECT * FROM users WHERE email = '$email' AND
password ='$password' LIMIT 1");
if(mysql_num_rows($result) > 0){
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$firstname = $row["firstname"];
echo "<BR>Login Successful, welcome";
echo $firstname;
}else{
echo 'wrong password/username combo';
}
Problem is Been here
$firstname = $_SESSION['firstname'];
$_SESSION['firstname']= $_POST['firstname'];
You are Trying to get First Name from login page html form. but i don't remember if any login page ever have First name field. so you should get first name from database and put it in $_SESSION['firstname']
Hope to be clear enough. :)
To get data out of database
Change this
SELECT count(*) FROM users WHERE email = '$email' AND password ='$password' LIMIT 1
To This
SELECT * FROM users WHERE email = '$email' AND password ='$password' LIMIT 1
$userdata = mysql_fetch_assoc($result);
$_SESSION['firstname'] = $userdata['firstname'];
This will do the trick
the place where you set your firstname should be changed with this
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$_SESSION['firstname']= $row['firstname'];
set firstname by fetching results from database because $_POST['firstname'] does not exists in your page.
Thanks.