How to check if username is already taken, PostgreSQL and php - php

I need to сheck if username is already taken or not. And if it is ok, to redirect to another page but if not (here I am stuck) to make the "username is already taken" appear under the input line.
there is my php code:
<?php
$host = "localhost";
$dbusername = "postgres";
$dbpassword = "admroot";
$db = "local_db_server_test";
$con = pg_connect("host=$host dbname=$db user=$dbusername password=$dbpassword") or die ("Could not connect to Server\n");
if(!$con){ die('Error: Unable to open database'); }
else {
$username = $_POST['username'];
$password = $_POST['password'];
if(strlen($password) < 6) {
pg_close($con); // also can use die() but without header and redirection
header("Location:sign_up_pass_err.html");
}
$query = "INSERT INTO register(username, password) VALUES ('$username',crypt('$password',gen_salt('md5')))";
$result = pg_query($con, $query);
header("Location: login.html");
}
pg_close($con);
?>
And this is my html code:
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="sign_up.php" method="post">
<input type="text" name="username" placeholder="Username" required><br><br>
<input type="password" name="password" placeholder="Password" required><br><br>
<input type="submit" value="Sign up">
</form>
</body>
</html>

Related

Can't enter data into sql database

I am using this code to add some data to my already existing sql database, but the can't seem to do so, it's also not giving any errors. I have tried everything that i could think of. This is a form which lets user input the data and then when user clicks submit it gives a success message in url but i get the success message but no data in my database.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Signup Form</title>
</head>
<body>
<form action="signup.php" method="POST">
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="email" placeholder="E-mail">
<br>
<input type="text" name="uid" placeholder="User name">
<br>
<input type="password" name="pwd" placeholder="Password">
<br>
<button type="submit" name="submit">Sign up</button>
</form>
<?php
$sql = "SELECT * FROM users;" ;
$result = mysqli_query($conn,$sql); //connects the database to the query we just generated
$resultcheck = mysqli_num_rows($result); // it returns the number of rows in the query
if($resultcheck > 0){
//the if condition checks if there is any data inside $resultcheck
//The mysqli_fetch_assoc() function fetches a result row as an associative array.
while($row = mysqli_fetch_assoc($result)){
echo $row['user_uid'].'<br>';
}
}
?>
</body>
</html>
<?php
include_once 'dbh.php';
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "INSERT INTO users (`user_firstname`, `user_firstname`, `user_email`, `user_uid`, `user_pwd` ) VALUES (\'$firstname\',\'$lastname\',\'$email\',\'$uid\', \'$pwd\');";
//require 'dbh.php';
mysqli_query('$conn','$sql');
/* if($result=$mysqli->query($sql)){
echo "<p>User successfully added to database</p>".'<br>';
}
else{
echo "Error enterting user into database!".mysql_error().'<br>';
} */
header("Location: index.php?signup=success");
?>
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "login_system"; // selecting the database
$conn = mysqli_connect($dbServername,$dbUsername,$dbPassword,$dbName );
//$mysqli = new mysqli('localhost','root',"",$dbName );
if(mysqli_connect_errno()){
printf("connection failed %s\n",mysqli_connect_error());
exit();
}
$mysqli->select_db("login_system");
?>
Please remove single quotes in $conn and $sql
mysqli_query($conn, $sql);
in your insert PHP file.
$sql = "INSERT INTO `users` (`user_firstname`, `user_lastname`, `user_email`, `user_uid`, `user_pwd` ) VALUES ('".$firstname."', '".$lastname ."', '".$email."', '".$uid."', '".$pwd."');";
$result=mysqli_query('$conn','$sql');
if($result)
{
echo "succsessfuly...";
}
else
{
echo "Not succsessfuly...";
}
Try this one:
<?php
include_once 'dbh.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Signup Form </title>
</head>
<body>
<form action="signup.php" method="POST">
<input type="text" name="firstname" placeholder="First Name">
<br>
<input type="text" name="lastname" placeholder="Last Name">
<br>
<input type="text" name="email" placeholder="E-mail">
<br>
<input type="text" name="uid" placeholder="User name">
<br>
<input type="password" name="pwd" placeholder="Password">
<br>
<button type="submit" name="submit">Sign up</button>
</form>
<?php
$sql = "SELECT * FROM users; " ;
$result = $mysqli->query($sql); //connects the database to the query we just generated
$resultcheck = $result->num_rows; // it returns the number of rows in the query
if($resultcheck > 0){
while($row = $result->fetch_assoc()){
echo $row['user_uid'].'<br>';
}
}
?>
</body>
</html>
signup.php
<?php
include_once 'dbh.php';
$firstname = $mysqli->real_escape_string($_POST['firstname']);
$lastname = $mysqli->real_escape_string($_POST['lastname']);
$email = $mysqli->real_escape_string($_POST['email']);
$uid = $mysqli->real_escape_string($_POST['uid']);
$pwd = $mysqli->real_escape_string($_POST['pwd']);
$sql = "INSERT INTO users (`user_firstname`, `user_lastname`, `user_email`, `user_uid`, `user_pwd` ) VALUES ('$firstname','$lastname','$email','$uid', '$pwd');";
if($result=$mysqli->query($sql)){
echo "<p>User successfully added to database</p>".'<br>';
}
else{
echo "Error enterting user into database!".$mysqli->error.'<br>';
}
header("Location: index.php?signup=success");
dbh.php
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "login_system"; // selecting the database
$mysqli = new mysqli($dbServername,$dbUsername,$dbPassword,$dbName);
if($mysqli->connect_errno){
printf("connection failed %s\n",$mysqli->connect_error);
exit();
}
Please read this reference http://php.net/manual/en/book.mysqli.php
should be like this
$sql = "INSERT INTO users (firstname, lastname, email, uid, pwd ) VALUES ('$firstname','$lastname','$email','$uid', '$pwd')";
mysqli_query($conn,$sql);

php password_hash and password_verify fail

Basic question but I keep failing. Have checked out similar topics but didn't get closer to the solution, so please don't redirect me just point out what I'm missing. Thank you.
<?php
$hashed_password = "";
$con = mysqli_connect("localhost", "root", "", "testTable");
if (isset($_POST["reg_button"])){
$password = ($_POST["reg_password"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = mysqli_query($con, "INSERT INTO user VALUES('', '$hashed_password')");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>register</title>
</head>
<body>
<form action="register.php" method="POST">
<input type="password" name="reg_password" placeholder="Password">
<br><br>
<input type="submit" name="reg_button" value="Register">
</form>
<br>
<form action="login.php" method="POST">
<input type="password" name="login_password" placeholder="Password">
<br><br>
<input type="submit" name="login_button" value="Login">
</form>
</body>
</html>
This is the registering part and it is working flawlessly. The provided password is getting hased and stored in the DB.
<?php
include "register.php";
$con = mysqli_connect("localhost", "root", "", "testTable");
if(isset($_POST["login_button"])){
$password = password_verify($_POST["login_password"], $hashed_password);
$checkDB = mysqli_query($con, "SELECT * FROM user WHERE password = '$password'");
$checkLogin = mysqli_num_rows($checkDB);
if($checkLogin == 1){
$row = mysqli_fetch_array($checkDB);
echo "Welcome";
}
else {
echo "Password incorrect";
}
}
?>
This is the login part and it always fails. I suspect the following snippet to be the culprit:
$password = password_verify($_POST["login_password"], $hashed_password);
but have no idea how to fix it.
Any help would be great. Thank you!
UPDATED CODE:
register.php:
<?php
$hashed_password = "";
$name = "";
$con = mysqli_connect("localhost", "root", "", "testTable");
if (isset($_POST["reg_button"])){
$password = ($_POST["reg_password"]);
$name = ($_POST["reg_name"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$query = mysqli_query($con, "INSERT INTO user VALUES('', '$name','$hashed_password')");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>register</title>
</head>
<body>
<form action="register.php" method="POST">
<input type="text" name="reg_name" placeholder="Name">
<br><br>
<input type="password" name="reg_password" placeholder="Password">
<br><br>
<input type="submit" name="reg_button" value="Register">
</form>
<br>
<form action="login.php" method="POST">
<input type="text" name="login_name" placeholder="Name">
<br><br>
<input type="password" name="login_password" placeholder="Password">
<br><br>
<input type="submit" name="login_button" value="Login">
</form>
</body>
</html>
login.php:
<?php
include "register.php";
$con = mysqli_connect("localhost", "root", "", "testTable");
if(isset($_POST["login_button"])){
$name = $_POST['login_name'];
$password = $_POST['login_password'];
$checkDB = mysqli_query($con, "SELECT * FROM user WHERE name = '$name'");
$passwordField = null;
while($getRow = mysqli_num_rows($checkDB)){
$passwordField = $getRow['password']; // Get hashed password
}
if(password_verify($password, $passwordField)){
echo('Correct');
}else{
echo('Wrong');
}
}
?>
Below from where do you get $hashed_password?Even if you included register.php,it doenst do anything,since those values are not set.
$password = password_verify($_POST["login_password"], $hashed_password);
You first need to get it from the db.
Second, password_verify returns true or false so even if $hashed_password is set,$password would be a boolean.
You can do this via while loop and mysqli_fetch_array(). That must solve your problem.: [UPDATED]
<?php
$con = mysqli_connect("localhost", "root", "", "testtable");
if(isset($_POST["login_button"])){
// $password = password_verify($_POST["login_password"], $hashed_password);
$password = $_POST['password'];
$checkDB = mysqli_query($con, "SELECT * FROM user");
while($getRow = mysqli_fetch_array($checkDB)){
$passwordRow = $getRow['password'];
}
if(password_verify($password, $passwordRow) === TRUE){
echo('Welcome');
}else{
echo('Wrong credentials');
}
}
?>

PHP file not working on webhosting service

This is my code (sorry for ill formatted code. I'm newbie to web development)
<html>
<head>
<?php
if (isset($_POST['login']))
{
$email = $_POST['email'];
$pass = $_POST['pass'];
$server='localhost';
$dbuser = 'database username';
$dbpass = 'database password';
$dbname = 'database name';
// Create connection
$conn = new mysqli($server, $dbuser, $dbpass, $dbname)
$sql = "INSERT INTO table (email, password)
VALUES ('$email','$pass')";
if ($conn->query($sql) === TRUE)
{
header('Location: address');
}
$conn->close();
}
?>
</head>
<body>
<form method="post" action="index.php">
email:<br>
<input type="text" name="email"><br>
password:<br>
<input type="password" name="pass"><br>
<input type = "submit" name="login" value="login">
</form>
</body>
</html>
I have saved this file as index.php in public_html and when I open my hosted website URL, it shows a blank page. Why?

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>

Adding user to MySQL database in php using phpMyAdmin

I think I am successfully connecting to my database by:
<?php
$user = 'root';
$pass = '9KSroMDjEqNmEYY4';
$db = 'chatservice';
$host = '127.0.0.1';
$conn = new mysqli($host, $user, $pass, $db, 3306) or die("Unable to connect");
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
?>
My question is how I would use the registration code to successfully add a user to the database. When entering the form I press register I do not get any error messages stating that the registration didn't succeed. It seems that the php code is not being reached after the initial connection. I am new to php and mySQL so any tips on formatting would be nice too!
<?php
require('connect.php');
if(isset($_POST['user']) && isset($_POST['password'])){
$user = $_POST['user'];
$id = $_POST['IDNUM'];
$password = $_POST['password'];
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', '$id', '$password')";
$result = mysqli_query($query);
if($result){
$msg = "Registered Sussecfully";
echo $msg;
}
else
$msg = "Error Registering";
echo $msg;
}
?>
<div class="register-form">
<title>Chat Page Start</title>
<form action="" methods="POST">
<p>
<label>Username: </label>
<input id="user" type="text" name="user" placeholder="user" />
</p>
<p>
<label>ID: </label>
<input id="IDNUM" type="text" name="IDNUM" placeholder="ID number" />
</p>
<p>
<label>Password: </label>
<input id="password" type="password" name="password" placeholder="password" />
</p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" value="Register" />
</form>
</div>
Another thing is how would I check the status of my database connection and where I should be checking this status?
your database connection is mysqli_connect and you execute the query in mysql_query is not proper.
<?php
require('connect.php');
if(isset($_POST['user']) && isset($_POST['password'])){
$user = $_POST['user'];
$id = $_POST['IDNUM'];
$password = $_POST['password'];
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', ' $id ', '$password')";
$result = mysqli_query($query,$conn);
if($result){
$msg = "Registered Sussecfully";
}
else
$msg = "Error Registering";
}
?>
You are connecting database using mysqli:
$conn = new mysqli('localhost', $user, $pass, $db, 3306) or die("Unable to connect");
And executing query using mysql:
$query = "INSERT INTO 'users' (user ,IDNUM ,password) VALUES('$user', '$IDNUM', '$password')";
$result = mysql_query($query);

Categories