Making sure that an username doesn't exit already with PHP - php

Im trying to making sure than when an user introduce a username in a form, that username is not already in my Database.
When I introduce a username that already exist, I get the error message: "* Username already exist". However, the username it is introduce in the database and therefore I have duplication in my database.
Also, anytime I update(F5) the browser a NULL record gets introduce in my database.
THANK YOU SO MUCH!!! :)
Below is the code I'm using:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$usernameErr = "";
$username = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$username)) {
$usernameErr = "Only letters, numbers and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
if ($usernameErr == '')
{
$db = pg_connect('host=localhost dbname=test user=myuser password=mypass');
$username = pg_escape_string($_POST['username']);
$query = "SELECT username FROM host";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
if ($username == $myrow[username]) {$usernameErr = "Username already exist";}
else { $query = "INSERT INTO host(username) VALUES('" . $username . "')";}
printf ("$myrow[username]>");
}
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
$username = "";
pg_close();
}
?>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>">
<span class="error">* <?php echo $usernameErr;?></span>
<br><br>
<input type="submit" name="submit" value="SAVE">
</form>
</body>
</html>

The problem is in the while statement; when it finds a coincidence in the database, it prints the 'User already exists' message, but instead of stopping the loop, it keeps comparing the username against the other records, which generate the inserted record. Change your while statement code to this:
while($myrow = pg_fetch_assoc($result)) {
if ($username == $myrow[username]) {
$usernameErr = "Username already exist";
break;
}
else {
$query = "INSERT INTO host(username) VALUES('" . $username . "')";
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
$username = "";
}
printf ("$myrow[username]>");
}
This should work for you. You can also define a unique constraint for the username column in your database.

ok, here is the solution that I found ant it is working for me.
Thank you
$usernamefound = false;
while($myrow = pg_fetch_assoc($result)) {
if ($username == $myrow[username]) {
$usernameErr = "Username already exist";
$usernamefound = true;
break;
}
}
if ($usernamefound == false) {
$query = "INSERT INTO host(username) VALUES('" . $username . "')";
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
$username = "";
}
printf ("$myrow[username]>");

Related

How to debug a mistake when inserting data into the table?

PHP code didn't insert.
<?php
$message = " ";
require "database.php";
if (isset($_POST["submit"])) {
if (empty($_POST["email"]) || empty($_POST["password"])) {
$message = "Email or Password is Incorrect";
} else {
$email = '$_POST[email]';
$pass = '$_POST[password]';
if ($email && $pass) {
$db = mysqli_select_db($conn, "auth");
$sqli = "INSERT INTO users (email, password) VALUES($email, $pass)";
if (mysqli_query($conn, $sqli)) {
$message = "New record created successfully";
} else {
$message = "Cannot create user!";
}
}
}
}
?>
$conn = mysqli_conncect("localhost","root","","auth");
I tried everything but not found the mistake to insert the query into the table.
Remove the single quotation in your else statement. PHP will interpret it as a string instead of a POST variable.
That is:
$email = $_POST['email'];
$pass = $_POST['password'];

SQL insert in php not working

Im very new to php and trying to get a register up and working , my code at the minute is only loading the username into the database and nothing else. Although it does enter values into other fields of the database if I hard-code them into sql insert and dont use
$users_Password
etc. btw I know this is terrible code and passwords should be hashed etc but ive literally just tore this code apart because this wont work and will add everything back in after this is sorted out cheers , this is my code
form
<form id = "Register_form" action="Register.php" method="post">
Username: <input type="text" name="Username"><br>
Password: <input type="password" name="Password"><br>
Confirm Password: <input type="password" name="ConfirmPassword"><br>
First Name: <input type="text" name="FirstName"><br>
Surname: <input type="text" name="Surname"><br>
Address Line 1: <input type="text" name="AddressLine1"><br>
Address Line 2: <input type="text" name="AddressLine2"><br>
City: <input type="text" name="City"><br>
Telephone: <input type="text" name="Telephone"><br>
Mobile: <input type="text" name="Mobile"><br></br>
<input type="submit">
then in the Register.php file
<?php
// create connection
$con=mysqli_connect("localhost","root","","book");
// check connection
if(mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$users_Username = $_POST['Username'];
$users_Password = $_POST['Password'];
$users_ConfirmPassword = $_POST['ConfirmPassword'];
$users_FirstName = $_POST['FirstName'];
$users_Surname = $_POST['Surname'];
$users_AddressLine1 = $_POST['AddressLine1'];
$users_AddressLine2 = $_POST['AddressLine2'];
$users_City = $_POST['City'];
$users_Telephone = $_POST['Telephone'];
$users_Mobile = $_POST['Mobile'];
//Multiple Error checkings such as
if ($users_Username == "")
{
echo "Please enter a username";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
else if ($users_Password = "")
{
echo "Please enter a password";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
else if ($users_ConfirmPassword == $users_Password)
{
if (strlen($users_Password)<=6)
{
$sql = "INSERT INTO users VALUES ('$users_Username', '$users_Password', '$users_FirstName', '$users_Surname','$users_AddressLine1','$users_AddressLine2','$users_City','$users_Telephone','$users_Mobile')";
if($con->query($sql) === TRUE)
{
echo "User succesfully registered";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Log_In_Screen.php';\",1500);</script>";
}
else
{
echo "Unable to register user, Please try again";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
//echo "<pre>\n$sql\n</pre>\n";
mysql_query($sql);
}
else
{
echo "The password you entered is too long, max characters is 6";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
}
else
{
echo "Passwords do not match, Please try again";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
mysqli_close($con);
?>
It seems like nothing will insert into the database except the username , any one have a way to fix this ?
Cheers
You had stuff all over the place and were mixing mysql and mysqli not to mention you left yourself wide open for SQL injection. Using the script you had I stuck with mysqli used prepared statements and split your validation and persistence up. There are comments that will explain some of this
<?php
$users_Username = $_POST['Username'];
$users_Password = $_POST['Password'];
$users_ConfirmPassword = $_POST['ConfirmPassword'];
$users_FirstName = $_POST['FirstName'];
$users_Surname = $_POST['Surname'];
$users_AddressLine1 = $_POST['AddressLine1'];
$users_AddressLine2 = $_POST['AddressLine2'];
$users_City = $_POST['City'];
$users_Telephone = $_POST['Telephone'];
$users_Mobile = $_POST['Mobile'];
//LETS JUST DO ERROR CHECKING ONLY
$valid = true; //Used to verify that user input is as expected.
//All the validation as before just as ifs and will set the
//$valid flag to false when validation fails.
if ($users_Username == "")
{
$valid = false;
echo "Please enter a username";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
if ($users_Password = "")
{
$valid = false;
echo "Please enter a password";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
if (strlen($users_Password)>6)
{
$valid = false;
echo "The password you entered is too long, max characters is 6";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
if ($users_ConfirmPassword != $users_Password)
{
$valid = false;
echo "Passwords do not match, Please try again";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
//Separating validation and persistence mean you only
//open a connection and persist when needed.
if($valid)
{
//NOW WE ONLY CONNECT WHEN YOU NEED TO!
$con=mysqli_connect("localhost","root","","book");
// check connection
if(!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//YOU MAY NEED TO SPECIFY THE COLUMNS YOU ENTER
$stmt = mysqli_prepare($con, "INSERT INTO users VALUES (?,?,?,?,?,?,?,?,?)");
//ASSUMING ALL 9 PARAMETERS ARE STRINGS hence the sssssssss
mysqli_stmt_bind_param($stmt, 'sssssssss', $users_Username,$users_Password,$users_FirstName,$users_Surname,$users_AddressLine1,$users_AddressLine2,$users_City,$users_Telephone,$users_Mobile);
if(mysqli_stmt_execute($stmt))
{
echo "User succesfully registered";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Log_In_Screen.php';\",1500);</script>";
}
mysqli_close($con);
}
?>
What content lands in your database?
Try the following in the appropriate line:
"INSERT INTO users VALUES ('".$users_Username."', '".$users_Password."', '".$users_FirstName."', '".$users_Surname."','".$users_AddressLine1."','".$users_AddressLine2."','".$users_City."','".$users_Telephone."','".$users_Mobile."')";
PHP Params cant be evaluated in ' ' so you have to use string concatenation.

I always get this error Warning: mysqli_num_rows() expects parameter 1

Here's the code and the defined variables too.
http://pastebin.com/t7nq8NJh
I've been trying to make it run for the past few hours already, and I just can't get past the area at line 32.
What do you think did I miss? I'm sorry, I am just starting to learn this so I might have missed some key structuring or something.
Thank you.
Code:
include_once('assets/inc/db_login.inc');
session_start();
function sql_entry($user,$pass,$phone,$points){
//do not touch anything beyond this part
$conn = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
//error catcher for connection failure
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
date_default_timezone_set('America/Chicago');
//grabs the time
$time = date('H:i:s');
//$time = $time->format();
$date = date('Y-m-d');
//$date = $date->format();
//clean themmmmmm!
$clean_user = mysqli_real_escape_string($conn, $user);
$clean_pass = mysqli_real_escape_string($conn, $pass);
$clean_phone = mysqli_real_escape_string($conn, $phone);
$clean_points = mysqli_real_escape_string($conn, $points);
//prepare queries
$verification = "SELECT * FROM ".DB_TBL."WHERE phone =".$clean_phone;
$verification_result = mysqli_query($conn,$verification); //run query to validate user
$count = mysqli_num_rows($verification_result); //
//error catcher for non-existing username or wrong user/pass
if($count < 1){
$account_registration = "INSERT INTO ".DB_TBL." (username,password,register_date,phone,points,notes) VALUES ('$clean_user','$clean_pass','$date','$clean_phone','$clean_points','')";
$registration_result = mysqli_query($conn,$account_registration);
mysqli_close($conn);
return 1;
}
else
mysqli_close($conn);
return 0;
}
//here's the other variables for login (all are correct, i have triple checked them already countless times)
<?php
define ("DB_HOST", "127.0.0.1");
define ("DB_USERNAME", "root");
define ("DB_PASSWORD", "ragnarok");
define ("DB_NAME", "houseofvbi");
define ("DB_TBL", "users");
?>
Additional:
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["name"])) {
$unameErr = "Username is required";
}
else {
$uname = clean_input($_POST["name"]);
}
if(empty($_POST["pass"])) {
$pwordErr = "Password is required";
}
else {
$pword = clean_input($_POST["pass"]);
}
if(empty($_POST["phone"])) {
$pwordErr = "Please input phone number";
}
else {
$phone = clean_input($_POST["phone"]);
}
if(empty($_POST["apass"])) {
$pwordErr = "Please input phone number";
}
else {
$points = clean_input($_POST["apass"]);
}
}
$check = sql_entry($uname,$pword,$phone,$points);
if($check == 0){
echo "<script type='text/javascript'>alert('The username is already in use.');";
echo "window.location = '#';";
echo "</script>";
}
else
echo "<script type='text/javascript'>alert('Registration is complete. You may log in in the game.');";
echo "window.location = '#';";
echo "</script>";
/* Functions */
function clean_input($login){
$login = trim($login);
$login = stripslashes($login);
$login = htmlspecialchars($login);
return $login;
}
In your query:
$verification = "SELECT * FROM ".DB_TBL."WHERE phone =".$clean_phone;
You need to add a space between TABLE NAME and WHERE as:
$verification = "SELECT * FROM ".DB_TBL." WHERE phone =".$clean_phone;
Second, don't know phone no field is string or integer if its string than you need to add single quote around phone no as:
$verification = "SELECT * FROM ".DB_TBL." WHERE phone = '$clean_phone'";

Checking if username exists POSTBACK

I want to check using the POSTBACK method i the user exists in mysql table. I studying mysql and i understand it will be removed soon but I cant change at the moment. I want the alert to pop up next to the username text box if it already exists.At the moment it isnt working. I have a similar code for password and password confirmation but i think this differs since i need a query. This is what i have:
<?php
$passErr = $pass1Err = "";
$passw = $passw1 = "";
$userErr="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["password"])) {
$passErr = "Password is required";
}
if (empty($_POST["passconfirm"])) {
$pass1Err = "Password confirmation is required";
}
if ($_POST['password']!= $_POST['passconfirm'])
{
$passErr = "Passwords must be the same";
$pass1Err = "Passwords must be the same";
}
}
else {
if (isset($_REQUEST["submit"]))
{
if (isset($_POST["submit"]))
{
$firstname = mysql_real_escape_string($_POST["gname"]);
$middlename = mysql_real_escape_string($_POST["mname"]);
$lastname = mysql_real_escape_string($_POST["surname"]);
$user = mysql_real_escape_string($_POST["username"]);
$addy = mysql_real_escape_string($_POST["address"]);
$post = mysql_real_escape_string($_POST["postcode"]);
$sta = mysql_real_escape_string($_POST["state"]);
$telephone = mysql_real_escape_string($_POST["tel"]);
$pass = mysql_real_escape_string($_POST["password"]);
$systemuser= mysql_real_escape_string($_POST["susername"]);
$sql2 = "SELECT username FROM users WHERE username= '$user'";
$rs = mysql_query($sql2, $conn)
or die ('Problem with query' . mysql_error());
$num_rows = mysql_num_rows($rs);
if(isset($_POST['username'])) {
if($num_rows != 0){
$userErr = "Username already exists";
}
}
}
}
mysql_close($conn);
}
?>
this is what i got in the form:
<label>Chosen Username:</label> <input type="text" name="username" value="<?php
echo $userErr;?>"/><span class="error">* <?php echo $userErr;?></span><br />
<label>Password:</label> <input type="password" name="password" value="<?php
echo $passw;?>"/><span class="error">* <?php echo $passErr;?></span><br />
<br />
<label>Password confirmation:</label> <input type="password" name="passconfirm" value="<?php
echo $passw1;?>"/><span class="error">* <?php echo $pass1Err;?></span><br />
To acheive what your looking for, instead of using
$num_rows = mysql_num_rows($rs);
if(isset($_POST['username'])) {
if($num_rows != 0){
$userErr = "Username already exists";
}
}
replace it with
$num_rows = mysql_num_rows($rs);
if(isset($_POST['username'])) {
$userErr = "Username field cannot be empty";
}elseif($num_rows > 0){
$userErr = "Username already exists";
}
That way if the Username field is empty, it will error out. And this will also achieve your goal of checking the database to see if the user exists or not.
You need to know if request with username return something so error messsage else do insert new user,
$sql2 = "SELECT * FROM users WHERE username= '$user'";
$rs = mysql_query($sql2, $conn) or die ('Problem with query' . mysql_error());
if($num_rows=mysql_fetch_array($rs)){
$userErr = "Username already exists";
// ....
} else{
// $SQL = "INSERT INTO users SET ...
}

Why won't the data be stored in my database? Error saying "You have an error in your SQL syntax;..."

Sorry I am new to php so please be patient with me. I am creating a user interface and when I register it says I have registered but it doesn't store the data into the database. Also every time I register at the moment it comes up with error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'testing101''' at line 1." Can someone please help me!
<?PHP
$uname = "";
$pword = "";
$errorMessage = "";
$num_rows = 0;
function quote_smart($value, $handle) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value, $handle) . "'";
}
return $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$uname = $_POST['username'];
$pword = $_POST['password'];
$uname = htmlspecialchars($uname);
$pword = htmlspecialchars($pword);
$uLength = strlen($uname);
$pLength = strlen($pword);
if ($uLength >= 10 && $uLength <= 20) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Username must be between 10 and 20 characters" . "<BR>";
}
if ($pLength >= 8 && $pLength <= 16) {
$errorMessage = "";
}
else {
$errorMessage = $errorMessage . "Password must be between 8 and 16 characters" . "<BR>";
}
if ($errorMessage == "") {
$user_name = "root";
$pass_word = "";
$database = "user authentication";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$uname = quote_smart($uname, $db_handle);
$pword = quote_smart($pword, $db_handle);
$SQL = "SELECT * FROM login WHERE USERNAME = '".$uname."'";
$result = mysql_query($SQL)or die(mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$errorMessage = "Username already taken";
}
else {
$SQL = "INSERT INTO login (USERNAME, PASSWORD) VALUES ('{$uname}', MD5('{$pword}'))";
$result = mysql_query($SQL);
mysql_close($db_handle);
//=================================================================================
// START THE SESSION AND PUT SOMETHING INTO THE SESSION VARIABLE CALLED login
// SEND USER TO A DIFFERENT PAGE AFTER SIGN UP
//=================================================================================
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
}
else {
$errorMessage = "Database Not Found";
}
}
}
?>
<html>
<head>
<title>Basic Login Script</title>
</head>
<body>
<FORM NAME ="form1" METHOD ="POST" ACTION ="signup.php">
Username: <INPUT TYPE = 'TEXT' Name ='username' value="<?PHP print $uname;?>" maxlength="20">
Password: <INPUT TYPE = 'TEXT' Name ='password' value="<?PHP print $pword;?>" maxlength="16">
<P>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Register">
</FORM>
<P>
<?PHP print $errorMessage;?>
</body>
</html>
You're double-quoting your text:
1 set of quotes gets added in your smart_quote() function.
1 set of quotes gets added in your actual query, so you're producting:
INSERT .... VALUES (''$uname'', ''$password'');
If you had proper error handling your query calls, you'd have seen this:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^

Categories