Checking if username is available - php

I am trying to check if the username is available before i insert into the table.
But it seems to insert into the table no matter if the username already exists.
Here is my php code:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'myPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
}
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
}
$username = $_POST['username'];
$password = $_POST['password'];
$name = $_POST['name'];
$email = $_POST['email'];
$username = mysqli_real_escape_string($link,$username);
$password = mysqli_real_escape_string($link,$password);
$name = mysqli_real_escape_string($link,$name);
$email = mysqli_real_escape_string($link,$email);
$password = md5($password);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count > 0) {
$sql = "INSERT INTO mainLogin (username, password, name, email) VALUES ('$username', '$password', '$name','$email' )";
$result = mysqli_query($link, $sql);
if (!$result) {
die('Error: ' . mysqli_error($link));
}else {
$_SESSION['login'] = $username;
echo "<script>window.location = 'http://madsanker.dk.linux101.unoeuro-server.com'</script>";
}
}else {
echo "username taken";
}
mysqli_close($link);
?>
What am I doing wrong?

just change the greater sign in your if statement from ">" to ==0
if($count==0){
}

If username already in db than change this condition:
if($count > 0) { 
//your stuff
}
With:
if($count <= 0) { // if not found
//your stuff
}

Related

I can't connect my database table to my website in order to register and sign in

My website fully functions on localhost but now that I put it on web hosting the account doesn't work, I cannot register or login. I know that it works because it previously did so there is a problem with the connection to the user table in my database. The other table with products is successfully connected. How do I fix this problem in my code?
<?php
include ('connect.php');
$conn = connect();
$email = $_POST['Email'];
$pass = $_POST['Password'];
$type = $_POST['type'];
if($type == "signup"){
$sql = $conn->prepare("SELECT * FROM user WHERE Email like ?");
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
echo "This email is already in use";
}
else{
/*Part 1*/
$sqlInsert = $conn->prepare("INSERT INTO `user` (`UID`, `Email`, `Password`, `FName`, `LName`, `Country`, `City`, `Address`) VALUES (NULL, ?, ?, '', '', '', '', '');");
$sqlInsert->bind_param('ss', $email, $pass);
$sqlInsert->execute();
echo "Success!";
}
}
else if($type == "login"){
$sql = $conn->prepare("SELECT * FROM user WHERE Email like ?");
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
if($row["Password"] == $pass){
// Log in
session_start();
$_SESSION['login_user'] = $email;
$_SESSION['account_id'] = $row["UID"];
echo "Success!";
}
else{
echo "Wrong credentials!";
}
}
}
else{
echo "Wrong credentials!";
}
}
mysqli_close($conn);
?>
I think the problem may be here
<?php
include 'config.php';
function connect() {
$conn = new mysqli(SERVER_NAME, USER, PASSWORD, DB_NAME);
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
return $conn;
}
?>
you can use this code please fill below fields
my_user: default 'root'
my_password: default ''
my_db: your database name
<?php
include 'config.php';
function connect()
{
$con = mysqli_connect("localhost", "root", "", "my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $con;
}
?>

My Webpage doesn't recognize the data fulfilled in a registration form

I'm currently doing a webpage, and by now I'm focused on the log in and registration forms. I have also a sql database connected. When I register a new user with the registration form, the database is updated succesfully. The problem is that when I try to log in with that user, the page doesn't recognize it. Besides, if I try to log in with an user that I introduced manually with Netbeans, it recognize it.
$con = mysqli_connect("localhost", "root", "mypassword");
if(!$con) {
exit('Connect Error (' . mysqli_connect_errno() .') ' . mysqli_connect_error());
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = mysqli_real_escape_string($con, htmlentities($_POST['new_mail']));
$password = mysqli_real_escape_string($con, htmlentities($_POST['new_passwd']));
$sql = "INSERT INTO usuarios (usuario, clave) VALUES ('". $user ."' , ' ".md5($password)."')";
mysqli_query($con, $sql);
if(mysqli_affected_rows($con) > 0) {
?>
<script type='text/javascript'>
alert('You have been registered succesfully. Now you can access our website');
</script>
<?php
header("Location: login_page.html");
echo "<br><br><a href='index.php'>Go back</a>";
} else {
if(mysqli_errno($con) == 1062) {
echo "The e-mail address introduced is already on the system.";
echo "<br><a href='register.html'>Try again</a>";
} else {
echo "Error: " .$sql . "<br>" . mysqli_error($con);
}
}
That's the code I use after fulfilling the registration form. The next one is the one I use after the log in form.
$con = mysqli_connect("localhost", "root", "mypassword");
if(!$con) {
exit('Connect Error (' . mysqli_connect_errno() .') ' . mysqli_connect_error());
}
if(mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = mysqli_real_escape_string($con, htmlentities($_POST['username']));
$password = mysqli_real_escape_string($con, htmlentities($_POST['password']));
$sql = "SELECT * FROM usuarios WHERE usuario='" . $user ."' AND clave='" . md5($password) . "'";
mysqli_query($con, $sql);
if(mysqli_affected_rows($con) > 0) {
//echo "Welcome " . $_SESSION['username'] . "!";
//echo "<br><br><a href='user_page.php'>Main Page</a>";
//echo "<br><a href= 'close_session.php'>Close Session</a>";
header("Location: main_page.html");
} else {
exit ("The user or password introduced are not correct");
}
$row = mysqli_fetch_row($sql);
$_SESSION['user'] = $row;
$_SESSION['username'] = $row[0];
mysqli_free_result($sql);
?>
Thank you for your help.
Few mistakes that you are doing on your registration page.
You are not using prepared statements.
You are using md5() instead of password_hash() and password_verify() to secure your passwords.
You are using cleansing mechanism on the password which you should't as this may change the original password.
With the above you should use prepared statements and take the advantage of password hash and verify,
therefore your register page. should look :
<?php
$con = mysqli_connect("localhost", "root", "mypassword");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = $_POST['new_mail'];
$password = $_POST['new_passwd'];
$hash = password_hash($password, PASSWORD_DEFAULT);
//check if user is not registered already, I'm not sure if you have user_id, what I know you should have id which is auto increment, then select that id
$sql = "SELECT user_id FROM usuarios WHERE usuario = ? ";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 's', $user);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
//user exists
echo "The e-mail address introduced is already on the system.";
echo "<br><a href='register.html'>Try again</a>";
} else {
//user does not exist register the user
$query = "INSERT INTO usuarios (usuario, clave) VALUES (?,?)";
$insert = mysqli_prepare($con, $query);
mysqli_stmt_bind_param($insert, "ss", $user, $hash);
if (mysqli_stmt_execute($insert)):
?>
<script type='text/javascript'>
alert('You have been registered succesfully. Now you can access our website');
</script>
<?php
header("Location: login_page.html");
echo "<br><br><a href='index.php'>Go back</a>";
else:
printf("Error: %s.\n", mysqli_stmt_error($insert));
endif;
}
?>
Then login
<?php
session_start();
$con = mysqli_connect("localhost", "root", "mypassword");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = $_POST['username'];
$password = $_POST['password'];
#ONLY SELECT THE SPECIFIC COLUMNS YOU NEED, DON'T USE#
$sql = "SELECT clave,anotherColumn,anotherColumn FROM usuarios WHERE usuario= ? ";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 's', $login);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$row = $row = mysqli_fetch_assoc($result);
if (password_verify($password, $row['clave'])) {
//passwords set sections, redirec
} else {
//user password does not match the stored hash return message
}
} else {
//username does not exist, do something
}
?>

Insert to table always failure

Its a simple registration with username and password, but when I try to insert it to the database it always fails and I don't know why, can someone help me with this?
include "db.php";
if (isset($_POST['submit']))
{
$username= $_POST['leguser'] ;
$password= $_POST['legpass'] ;
$pwhash = password_hash($password, PASSWORD_DEFAULT) ;
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
echo var_dump ($username);
echo var_dump ($password);
echo var_dump ($pwhash);
$sql = "SELECT * FROM tbl_users WHERE fld_username = '$username'";
$result = $conn->query($sql);
if ($result->num_rows === 1) {
echo "<script>alert('Username already used!');</script>"; }
else
{
$q = "INSERT INTO `tbl_users` (`fld_username`) VALUES ('$username')";
$result = mysql_query($q);
if ($result) {
echo 'success';
} else {
echo 'failure';
}
}
This is the code of the database connection (db.php)
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'rsi_db';
$conn = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($conn->connect_errno > 0) {
die('Connection failed [' . $conn->connect_error . ']');
}
By the way I only want to input only one data on the database which is the username, for me not to get complicated with every data that I want to put in the future.

Undefined index: userID error

Upon Logging in, I have the userID stored in the SESSION. However when I call updateMarkerlocations.php it says userID is undefined. Not sure what I'm missing.
login.php
session_start();
if (!isset($_POST['submit'])){
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from userinfo WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
$row = $result->fetch_assoc();
setcookie("username", time() +60*60*24*30*365);
$_SESSION['userID'] = $row['userID'];
echo "<p>Logged in successfully!, Please close the window</p>";
}
}
?>
updateMarkerLocations.php
<?php
include 'db_const.php';
function insertMarkerLocations()
{
$markerCount = 0;
if (isset($_POST['markerCount']))
$markerCount = $_POST['markerCount'];
if(isset($_SESSION["userID"]))
{
$userID = $_SESSION["userID"];
}
$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME);
$userID = $_POST['userID'];
for($i=0 ; $i < $markerCount; $i++){
$index = $i;
++$index;
$curMarkerID = $_POST["markerID$index"];
$curLang = $_POST["lang$index"];
$curLat = $_POST["lat$index"];
// Now write the current marker details in to the db.
$query = "INSERT INTO userinfo (userID, markerID, lang, lat ) VALUES ('$userID', '$curMarkerID', '$curLang', '$curLat')";
mysql_query($query)
or die(mysql_error());
}
$msg = "SUCCESS";
return $msg;
}
$msg = insertMarkerLocations();
echo json_encode($msg);
?>
Add this at the top of each file:
if(!isset($_SESSION)) session_start();
Also, when you do:
$userID = $_POST['userID'];
you should ensure that $_POST['userID'] exists:
if(isset($_POST['userID'])) $userID = $_POST['userID'];

Simple php/mysql not working

I have the following in a php script.All I get is a blank page, no errors or nothing.
error_reporting(E_ALL);
ini_set("display_errors", 1);
$database = "mydatabase";
$con = mysql_connect("localhost", "admin", "password") or die(mysql_error());
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db($database);
if(!$db){
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['id'])){
$userid = mysql_real_escape_string($_POST['id']);
echo($userid);
}
if(isset($_POST['name')){
$username = mysql_real_escape_string(htmlentities($_POST['name']));
echo($username);
}
$query = mysql_query("SELECT * FROM userinfo
WHERE userid ='$userid'")or die(mysql_error());
if(mysql_num_rows($query) > 0){
echo "yeah";
}else{
$query = mysql_query("INSERT INTO userinfo (username,userid)
VALUES ($username,$userid)")or die(mysql_error());
if(mysql_affected_rows($query)== 1){
echo "UPDATED";
}else{
echo "NOPE";
}
}
You should format your code better. Also you where missing a close ] bracket on this line, if (isset($_POST['Name')) {
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$database = "mydatabase";
$con = mysql_connect("localhost", "admin", "password") or die(mysql_error());
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db = mysql_select_db($database);
if(!$db)
{
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['id']))
{
$userid = mysql_real_escape_string($_POST['id']);
echo($userid);
}
if(isset($_POST['name']))
{
$username = mysql_real_escape_string(htmlentities($_POST['name']));
echo($username);
}
$query = mysql_query("SELECT * FROM userinfo WHERE userid ='$userid'")or die(mysql_error());
if(mysql_num_rows($query) > 0)
{
echo "yeah";
}
else
{
$query = mysql_query("INSERT INTO userinfo (username,userid) VALUES ($username,$userid)")or die(mysql_error());
if(mysql_affected_rows($query)== 1)
{
echo "UPDATED";
}
else
{
echo "NOPE";
}
}
?>
You also have an error in your SQL:
INSERT INTO userinfo (username,userid)
VALUES ($username,$userid)
The values here should be quoted:
INSERT INTO userinfo (username,userid)
VALUES ('$username', '$userid')

Categories