Registration Form Works but shows error - php

I made a registration form. it actually works but it shows the "Failed To Register, Try Again" message.
Here's my code.
HTML and PHP
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="#" method="POST">
<h3>Register</h3>
Username: <input type="text" name="uname"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" name="btn">
</form>
</body>
</html>
<?php
if (isset($_POST['btn'])) {
$username = $_POST['uname'];
$password = $_POST['pass'];
mysql_connect("localhost","root","");
mysql_select_db("login2");
$query = "INSERT INTO users VALUES ('','$username','$password')";
mysql_query($query);
echo "Registered Successfully";
}
else {
echo "Failed To Register, Try Again";
}
?>

You can check the post.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
Also add uname and pass control.

<?php
if (isset($_POST['uname']) && !empty($_POST['uname']) && isset($_POST['pass']) && !empty($_POST['pass'])) {
$username = $_POST['uname'];
$password = $_POST['pass'];
............................
}
else {
echo "Failed To Register, Try Again";
}
?>

1.There is a problem with you if statement which shows failed to register on page load
Mysql is deprecated, use mysqli_*.
Here is an updated code
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="#" method="POST">
<h3>Register</h3>
Username: <input type="text" name="uname"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" name="btn" value="Submit">
</form>
</body>
</html>
<?php
if (isset($_POST['btn'])) {
$username = $_POST['uname'];
$password = $_POST['pass'];
mysqli_connect("localhost","root","");
mysqli_select_db("login2");
$query = "INSERT INTO users VALUES ('','$username','$password')";
$results=mysqli_query($query);
if(mysqli_affected_rows($con)>0){ //check if inserted
echo "Registered Successfully";
}
else{
echo "Failed To Register, Try Again";
}
}
?>

Try the below code and check
<?php
if (isset($_POST['btn'])) {
$username = $_POST['uname'];
$password = $_POST['pass'];
mysql_connect("localhost","root","");
mysql_select_db("login2");
$query = "INSERT INTO users VALUES ('','$username','$password')";
if(mysql_query($query))
{
echo "Registered Successfully";
}
else
{
echo "Failed To Register, Try Again";
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="#" method="POST">
<h3>Register</h3>
Username: <input type="text" name="uname"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" name="btn">
</form>
</body>
</html>
<?php
if (isset($_POST['btn']))
{
$username = $_POST['uname'];
$password = $_POST['pass'];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users(`username`, `password `) VALUES ('$username','$password ')";
$result = $conn->query($sql);
if (!$result)
{
echo("Error description: " . mysqli_error($conn));
}
else
{
echo "successfully inserted";
}
}
?>

Related

Unable to send data from html form into mysql

I am unable to send the information from a from into mysql. I get the following error:
Fatal error: call to undefined function mysqli_connect()
I know the db connection is working because I am able to send other data into the database. I have added the connection information on the signupcontact.php but that did nothing.
I am not sure what the issue is since the database is connected.
Thanks for your help in advance.
form:
<?php
echo "<div class='wrapper'>";
require ('header.php');
include ('signupcontact.php');
include ('db_connect2.php');
?>
<head>
<title>Contac Information</title>
<meta charset="utf-8"/>
<link rel="stylesheet" href="style.css"/>
</style>
<script>
function validateForm() {
if (document.forms[0].userName.value == "") {
alert("Name field cannot be empty.");
return false;
} //end if
if (document.forms[0].userLastName.value == "") {
alert("Last Name field cannot be empty.");
return false;
} // end if
if (document.forms[0].userEmail.value == "") {
alert("Email field cannot be empty.");
return false;
} // end if
alert ("Successful!");
return true;
} //end function validateForm
</script>
</head>
<body>
<?php
echo '<form method="POST"
action="db_connect2.php"
onsubmit="return validateForm();">
<fieldset style="width:900px; margin:auto;">
<legend class="pcenter">Subscribe for updates</legend>
<label for="userName">Name: </label><br />
<input type="text" name="userName" id="userName"/><br /><br />
<label for="Last_Name">Last Name: </label><br />
<input type="text" name="userLastName" id="userLastName"/><br /><br />
<label for="userEmail">Email: </label><br />
<input type="text" name="userEmail" id="userEmail"/>
<br /><br />
<input type="submit" value="submit" id="submit"/><br />
</fieldset>
</form>
dbconnect:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'happy_blog');
if(!$conn) {
die("connection failed: ".mysqli_connect_error());
}
signupcontact (I added the connection here again to see if it helps, nothing)
<?php
$dBServername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "happy_blog";
// Create connection
$conn = mysqli_connect($dBServername, $dBUsername, $dBPassword, $dBName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['submit'])){
$Name = $_POST['userName'];
$LName = $_POST['userLastName'];
$Email = $_POST['userEmail'];
$Name = mysqli_real_escape_string($conn,$_POST['userName']);
$LName = mysqli_real_escape_string($conn,$_POST['userLastName']);
$Email = mysqli_real_escape_string($conn,$_POST['userEmail']);
//$sql = "INSERT INTO contact (userName, userLastName, userEmail) VALUES ('".$_POST["userName"]."', '".$_POST["userLastName"]."', '".$_POST["userEmail"]."')";
$sql = "INSERT INTO contact (userName, userLastName, userEmail) VALUES ($Name, $LName, $Email)";
$result = mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "Form submitted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}

How to display a page if the user is logged in

I have a basic login where the code redirects the user to a page (google.com at the moment). How do I make it so that the page it redirects you to is only accessible if the user is logged in (they can't just type the URL and access the page). I understand that you have to use session start but have read around and cannot come up with a solution.
login.php
<?php
error_reporting(E_ALL | E_STRICT);
$servername = "localhost";
$serverUsername = "root";
$serverPassword = "";
// Create connection
$conn = new mysqli($servername, $serverUsername, $serverPassword, "users");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$loginError = "";
if (isset($_POST["submit"])) {
$username = $conn->real_escape_string($_POST["username"]);
$stmt = $conn->prepare("SELECT Password FROM user_logons WHERE Username = ? LIMIT 1");
$stmt->bind_param("s", $username);
$stmt->bind_result($password);
$stmt->execute();
$stmt->fetch();
$stmt->close();
if (password_verify($_POST['password'], $password)) {
header("Location: https://google.com/");
}
else {
$loginError = "Invalid username or password!";
}
}
mysqli_close($conn);
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Login Test</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username: <input type="text" name="username">
<br><br>
Password: <input type="password" name="password">
<br><br>
<input type="submit" name="submit" value="Submit">
<span class = "error"><?php echo $loginError; ?></span>
</form>
</body>
</html>
login.php
<?php
error_reporting(E_ALL | E_STRICT);
$servername = "localhost";
$serverUsername = "root";
$serverPassword = "";
// Create connection
$conn = new mysqli($servername, $serverUsername, $serverPassword, "users");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$loginError = "";
if (isset($_POST["submit"])) {
$username = $conn->real_escape_string($_POST["username"]);
$stmt = $conn->prepare("SELECT Password FROM user_logons WHERE Username = ? LIMIT 1");
$stmt->bind_param("s", $username);
$stmt->bind_result($password);
$stmt->execute();
$stmt->fetch();
$stmt->close();
if (password_verify($_POST['password'], $password)) {
session_start();
$_SESSION["loggedIn"] = "true";
header("Location: redirect.php");
}
else {
$loginError = "Invalid username or password!";
}
}
mysqli_close($conn);
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Login Test</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username: <input type="text" name="username">
<br><br>
Password: <input type="password" name="password">
<br><br>
<input type="submit" name="submit" value="Submit">
<span class = "error"><?php echo $loginError; ?></span>
</form>
</body>
</html>
redirect.php
<?php
error_reporting(E_ALL | E_STRICT);
session_start();
if(!empty($_SESSION['loggedIn'])) {
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
</style>
</head>
<body>
<h1>Welcome User<h1>
</body>
</html>
<?php
}
else {
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h1 align = "center">Unfortunately, you will need to be logged in to view this section!<h1>
<p align = "center">To return to the login page Click Here</p>
</body>
</html>
<?php
}
session_destroy();
?>

How to set up a login system using PHP and Mysql?

I am trying to set up a login system but the page is not doing the validation of the user and passwors. I know is connecting to the database but it doesn't show any results after the for each statement.
I have two files one for the login form(login.php) and one for the login to the database(process.php).
Here is my code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Login Page</title>
</head>
<body>
<div>
<form action="process.php" method="POST">
<p>
<label>Username:</label>
<input type="text" id="user" name="user">
</p>
<p>
<label>Password:</label>
<input type="password" id="pass" name="pass">
</p>
<p>
<label>Username:</label>
<input type="submit" id="btn" value="Login">
</p>
</form>
</div>
</body>
</html>
Process.php
<?php
//Get values from login.php file
$username = $_POST['user'];
$password = $_POST['pass'];
//Stop SQL injection
/* $username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);*/
//Connect to the server and select database
$domainsn = 'mysql:host=localhost;dbname=login';
$username = 'root';
$password = 'costarica';
try {
$db = new PDO ($domainsn, $username, $password);
echo "Connected";
} catch (Exception $e) {
$error_message = $e->getMessage();
echo "Coudn't connect due to $error_message";
}
$query = "SELECT * FROM users WHERE username = '$username' AND password ='$password'";
$result = $db->query($query);
//echo "$result";
foreach ($result as $results) {
echo "$results";
echo $users['id'];
if ($results['username'] == $username && $results['password'] == $password) {
echo "Login success!!! Welcome ".$results['username'];
} else {
echo "failed try {} catch ( $e) {}";
}
}
?>`enter code here`
You can use this i hope it will help.
$query = "SELECT * FROM users WHERE username = '".$username."' AND password ='".$password."' ";
$result = $db->query($query);
if($result->num_rows>0){
// User exists
}else{
// User not exists.
}

Login & Register System

I have a little problem with my Login & Register System but I don't know where the problem is. When I press "Login" or "Register", the next page is white. I see only my message: "Try again!". I made 3 PHP files:
1) index.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="logreg.php" metodh="post" accept-charset="utf-8">
<label>Username:</label><input type="text" name="username" placeholder="Username">
<br>
<label>Password:</label><input type="password" name="password" placeholder="Password">
<br>
<input type="submit" name="login" value="Login">
<input type="submit" name="register" value="Register">
</form>
</body>
</html>
I think the problem is in the next file:
2) logreg.php
<?php
$servername = "localhost";
$username = "alex";
$password = "calamar28";
$database = "register/login";
$conn = mysqli_connect($servername, $username, $password, $database );
if(!$conn){
die("Connection failde:".mysqli_connect_error());
}
if(isset($_POST["login"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass';";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count == 1)
{
header("Location: personal.php");
}
else
{
echo "Username or password is incorrect!";
}
}
else if(isset($_POST["register"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "INSERT INTO users (id, username, password) VALUES ('', '$user', '$pass')";
$result = mysqli_query($conn, $sql);
}
else
{
echo "Try again!";
}
?>
3) personal.php
<?php
if(isset($_POST["login"])){
echo "Welcome to you personal area !";
echo 'Your proiect';
}
else
{
echo "You are not logged in!";
}
?>
You will also need to set some session variables to carry through onto the personal.php page... This will help determine if the user has logged in successfully or not as the original posted data won't be transferred through when you redirect to this page... You'll want your logreg.php to be the following:
<?php
if (!isset($_SESSION)) {session_start();}
$servername = "localhost";
$username = "alex";
$password = "calamar28";
$database = "register/login";
$conn = mysqli_connect($servername, $username, $password, $database );
if(!$conn){
die("Connection failde:".mysqli_connect_error());
}
if(isset($_POST["login"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass';";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count == 1)
{
$_SESSION['loggedIn'] = 1;
header("Location: personal.php");
}
else
{
echo "Username or password is incorrect!";
}
}
else if(isset($_POST["register"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "INSERT INTO users (id, username, password) VALUES ('', '$user', '$pass')";
$result = mysqli_query($conn, $sql);
}
else
{
echo "Try again!";
}
?>
And then your personal.php page will change to the following:
<?php
if (!isset($_SESSION)) {session_start();}
if(isset($_SESSION["loggedIn"]) && ($_SESSION["loggedIn"] == 1) ){
echo "Welcome to you personal area !";
echo 'Your proiect';
}
else
{
echo "You are not logged in!";
}
?>
The Default Method for HTML Forms is GET. And in your HTML Code you wrote metodh instead of method. This would be ignored and then your method would automatically default to GET. Other than this, your PHP Code is fine.
Change your HTML Code to look something like below and everything should work fine as expected:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="logreg.php" method="post" accept-charset="utf-8">
<label>Username:</label><input type="text" name="username" placeholder="Username">
<br>
<label>Password:</label><input type="password" name="password" placeholder="Password">
<br>
<input type="submit" name="login" value="Login">
<input type="submit" name="register" value="Register">
</form>
</body>
</html>

PHP login form not functioning [duplicate]

This question already has answers here:
Login page not functioning
(2 answers)
Closed 7 years ago.
I have written code for a login page in PHP. When I submit the log in details, the page is simply being redirected to itself even though I have written a code to redirect to a different page. Please help me identify where the mistake is.
The code looks like this
<?php
session_start();
$username = $password= "";
$usernameErr = $passwordErr = "";
$empty = false;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty($_POST["username"]))
{
$empty = true;
$usernameErr="Username is empty. Please try again";
}
else
{
$username = $_POST["username"];
}
if(empty($_POST["password"]))
{
$empty = true;
$passwordErr="Password is empty. Please try again";
}
else
{
$password = $_POST["password"];
}
if(!$empty)
{
$servername = "myxor.in.mysql";
$dbusername = "myxor_in";
$dbpassword = "srikanth177";
$dbname = "myxor_in";
// Create connection
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT firstname,password,package FROM users WHERE username='$username'";
$result = $conn->query($sql);
if (($result->num_rows) > 0)
{
$row = $result->fetch_assoc();
if($username === $row['username'])
{
if($password === $row['password'])
{
echo "came here";
$_SESSION['fname'] = $row['firstname'];
$_SESSION['pack'] = $row['package'];
$_SESSION['login_user'] = $username;
header("Location: http://www.myxor.in/home.php");
}
else
{
$passwordErr = "Invalid Password. Please Try Again";
}
}
} else
{
$usernameErr = "Invalid Username. Please Try Again";
}
}
}
?>
<head>
<style>
td{
color:red;
}
</style>
<title>Login Page</title>
</head>
<body>
<h2 align=center style="color:blue">Login Form</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<table align=center bgcolor=grey >
<tr>
<td><label>UserName :</label>
<td><input id="name" name="username" placeholder="username" type="text">
<td><?php echo $usernameErr?></td>
<tr>
<td><label>Password :</label>
<td><input id="password" name="password" placeholder="**********" type="password">
<td><?php echo $passwordErr?></td>
<tr>
<td colspan=2 align=center><input name="submit" type="submit" value=" Login ">
</table>
</form>
</body>
</html>
This is where the problem is:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
You are sending the form to the same url the form is being displayed with $_SERVER["PHP_SELF"] (which is actually valid unless you want to send the form to another URL like in your case). Change the action to the URL you want to send the form to for validation. E.g.
<form action="validate_form.php" method="post">
.....
Or you can do this:
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
Try this:
<?php
session_start();
include("validations.php");
$username = "";
$password= "";
$usernameErr = $passwordErr = "";
$empty = false;
if(isset($_POST['submit'])
{
if(empty($_POST["username"]))
{
$empty = true;
$usernameErr="Username is empty. Please try again";
}
else
{
$username = $_POST["username"];
}
if(empty($_POST["password"]))
{
$empty = true;
$passwordErr="Password is empty. Please try again";
}
else
{
$password = $_POST["password"];
}
if(!$empty)
{
$servername = "myxor.in.mysql";
$dbusername = "myxor_in";
$dbpassword = "srikanth177";
$dbname = "myxor_in";
// Create connection
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT firstname,password,package FROM users WHERE username='$username'";
$result = $conn->query($sql);
if (($result->num_rows) > 0)
{
$row = $result->fetch_assoc();
if($username === $row['username'])
{
if($password === $row['password'])
{
echo "came here";
$_SESSION['fname'] = $row['firstname'];
$_SESSION['pack'] = $row['package'];
$_SESSION['login_user'] = $username;
header('Location: http://www.myxor.in/home.php');
exit;
}
else
{
$passwordErr = "Invalid Password. Please Try Again";
}
}
} else
{
$usernameErr = "Invalid Username. Please Try Again";
}
}
}
?>
<head>
<style>
td{
color:red;
}
</style>
<title>Login Page</title>
</head>
<body>
<h2 align=center style="color:blue">Login Form</h2>
<form action="this_page.php" method="post">
<table align=center bgcolor=grey >
<tr>
<td><label>UserName :</label>
<td><input id="name" name="username" placeholder="username" type="text">
<td><?php echo $usernameErr?></td>
<tr>
<td><label>Password :</label>
<td><input id="password" name="password" placeholder="********** type="password">
<td><?php echo $passwordErr?></td>
<tr>
<td colspan=2 align=center><input name="submit" type="submit" value=" Login ">
</table>
</form>
</body>
</html>
And you had: $username = $password = "";
I corrected it to $username = ""; $password="";
And I changed some of the html
What I changed in the html is the form action to be a page not just <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
I changed it to: <form action="yourpagevalidation.php" method="post">
And I added exit after your header
And I changed Your if($_REQUEST[] stuff to if(isset($_POST['submit']))
Thank you guys for your help. I found the error myself. The error is that I am trying to access 'username' from the row without selecting username in the query. So it is malfunctioning. I rectified it by adding username column in the select list. Thank you again.

Categories