Checking if username exists POSTBACK - php

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 ...
}

Related

MYSQL is automatically decrypting my password upon record entry

I have a script that adds an email address and password to a table. I first search to see if the email address exists in the table. If it does, I give an error message. If it does not, I add the record.
Then, using mysqli_insert_id(), I run another query to update the record I just added, encrypting the password with md5.
But every time I run it, the record is added, but the password does not get updated with the md5 version of the password. I have echo'd the query and it shows that it should be updating the password with the encryption, but it doesn't. Any ideas?
<?php
session_start();
error_reporting(E_ALL);
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "eits_Admin", "WebSpinner1", "EITS_Sandbox");
if (!$link) {
die("Database connection error");
}
$error = '';
if (!$_POST['email']) {
$error .= "<br/>An email address is required";
}
if (!$_POST['password']) {
$error .= "<br/>A password is required";
}
if ($error != "") {
$error = "There were errors in your form - ".$error;
} else {
$query = "select id from secretdiary
where email = '".mysqli_real_escape_string($link, $_POST['email'])
."' limit 1";
// echo $query;
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is not available.";
} else {
$query = "insert into secretdiary
(email,password)
values ('" . mysqli_real_escape_string($link, $_POST['email'])
. "', '"
. mysqli_real_escape_string($link, $_POST['password']) . "')";
if (!mysqli_query($link, $query)) {
$error = "Could not sign you up at this time. Please try again later.";
} else {
$encPass = md5(md5(mysqli_insert_id($link)) . $_POST['password']);
$query = "update secretdiary
set password = '" . $encPass
. "' where id = " . mysqli_insert_id($link) . " limit 1";
echo $query;
$result = mysqli_query($link,$query);
echo "Sign up successful.";
}
}
}
}
?>
<div id="error"><? echo $error; ?></div>
<form method="post">
<input type="email" name="email" placeholder= "Your Email">
<input type="password" name="password" placeholder="Password">
<input type="checkbox" name="stayLoggedIn" value=1>
<input type="submit" name="submit" value="Sign Up!">
</form>
You've got a lot of lines of code for a relatively simple process. Personally your form error handling such as if it's empty (in this case) can be remedied by adding required at the end of each HTML form input element (This is what I'd do)
Secondly, md5 isn't safe for hashing passwords (you're hashing a password not encrypting it)
Thirdly here's a way to hash the password from the form using Bcrypt which is much better than using md5 hashing. So do whatever error checking you need to do before like counting the usernames and if row > 0 die('username exists) Example of full code at base using PDO
When checking the users login simply use password_verify() function to do so
Tidy code helps people on SO understand what your problem is and is generally nicer to read. I know you may just be looking for something that 'Does the job' But it helps you when debugging and us when you're asking for help.
I'm going to give you a way that is marginally more secure than your one.
index.php
<form method="post" id="regform" action="register.php">
<input type="text" name="username" placeholder="Enter your email Address"required/>
<input type="password" name="password" placeholder="Enter your password" required/>
<input type="submit" class="indexbttn" id="indexbttn" name="enter"value="enter"/>
</form>
connect.php
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "fyp";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
?>
register.php
<?php
session_start();
require_once ('connect.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$check (!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL));
$cnt = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($cnt);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('That username already exists!');
}
$passHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$insrt = "INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $pdo->prepare($insrt);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passHash);
$result = $stmt->execute();
if($result){
header( "refresh:5;url=index.php" );
echo 'You will be redirected in 5 seconds. If not, click here.';
}
}
?>
login.php
<?php
session_start();
require("connect.php");
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$rtrv = "SELECT username, password, userid FROM users WHERE username = :username";
$stmt = $pdo->prepare($rtrv);
//Bind value.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE.
if($user === false){
//Could not find a user with that username!
die('Incorrect username');
}
else{
$validPassword = password_verify($pass, $user['password']);
if($validPassword){
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /protected.php" );
die();
} else{
die('Wrong password!');
}
}
}
?>

Connection between login page and register

I am new to php, I'm trying to link the login page and register page. Once I press the login button it goes directly to the linked page although I enter wrong password.
I tried to solve it by putting mysqlinumrows. The result after login is still in the login page . I've tried to fix it, but can't. I hope someone will help me to reduce my stress by knowing my fault in the code below I attach.
Code:
<?php
session_start();
$_SESSION['message'] = '';
$mysqli=new MySQLi('127.0.0.1','root','','accounts');
if($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST['password']== $_POST['confirmpassword']) {
$username = $mysqli->real_escape_string($_POST['username']);
$email = $mysqli->real_escape_string($_POST['email']);
$password = md5($_POST['password']);
$profile_path = $mysqli->real_escape_string('images/'.$_FILES['profile']['name']);
if (preg_match("!image!", $_FILES['profile']['type'])) {
if (copy($_FILES['profile']['tmp_name'],$profile_path)){
$_SESSION['username'] =$username;
$_SESSION['profile'] =$profile_path;
$sql ="INSERT INTO users(username,email,password,profile)"
."VALUES ('$username','$email','$password','$profile_path')";
if($mysqli->query($sql)=== true) {
$_SESSION['message'] = 'Registration successful!
Added $username to the database!';
header("location:RegisterLogin.php");
}
else {
$_SESSION['message'] = "User could not be added to the database!";
}
}
else{
$_SESSION['message'] = "file failed!";
}
}
else {
$_SESSION['message'] = "Please only upload GIF,JPG, or PNG images!";
}
}
else{
$_SESSION['message'] = "two password do not match!";
}
}
?>
(Login Form)
<?php
session_start();
$_SESSION['message']='';
$mysqli=new MySQLi('127.0.0.1','root','','accounts');
if(isset($_POST['username'])) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$sql="SELECT * FROM users WHERE username ='$username' AND password=$password";
$result = mysqli_query($mysqli,$sql);
if(mysqli_affected_rows($result) == 1){
$_SESSION['username'] = $username;
$_SESSION['message'] = "Registration successful!";
header("location:Welcome.php");
}
else{
$_SESSION['message'] = "Login Failed!";
}
}
?>
Correct your select query in login page to $sql="SELECT * FROM users WHERE username ='$username' AND password='$password' "; Add single quotes to password variable
First you must have form tag. try this format
<form action="" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="login">
</form>
And for your PHP code:
if(isset($_POST['login'])) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($_POST['password']);
$sql="SELECT * FROM users WHERE username ='$username' AND password=$password";
$result = mysqli_query($mysqli,$sql);
if(mysqli_affected_rows($result) == 1){
$_SESSION['username'] = $username;
$_SESSION['message'] = "Registration successful!";
header("location:Welcome.php");
}
else{
$_SESSION['message'] = "Login Failed!";
}
}
If It's not your problem then comment it below. I'll help you.

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.

check if profile data exists on profile update

I have a profile page, function for the edit and a check function for the edit.
profile page:
if (isset($_POST['edit']) && $_POST['edit'] === 'Edit') {
$errorMsgs = $user->validateUpdate($_POST);
if (empty($errorMsgs)) {
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
$user->updateProfile($username,$email,$id);
echo 'edited';
exit;
}
foreach ($errorMsgs as $msg) {
echo '<li>'. $msg. '</li>';
}
}
while ($row = mysqli_fetch_assoc($result)) {
?>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
Username<br>
<input type="text" name="username" value="<?php echo $row['username']; ?>" /><br>
Email<br>
<input type="text" name="email" value="<?php echo $row['email']; ?>" /><br>
<input name="edit" type="submit" value="Edit"/>
</form>
<?php }
?>
Update function:
function updateProfile($username,$email,$id){
$con = new Core();
$con->connect();
$username = trim(strtolower($username));
$username = str_replace(' ', '', $username);
$sql = 'UPDATE users SET username = ?, email = ? where id = ?';
if ($stmt = $con->myconn->prepare($sql))
{
$stmt->bind_param('ssi', $username, $email, $id);
$stmt->execute();
$stmt->close();
}
else{
die("errormessage: " . $con->myconn->error);
}
}
Check function:
function validateUpdate(array $userDetails)
{
$con = new Core();
$con->connect();
$errmsg_arr = array();
foreach($userDetails as $key => $value) {
if (empty($value)) {
$errmsg_arr[] = ucwords($key) . " field is required";
}
}
if (!empty($userDetails['edit'])) {
if (!empty($userDetails['email']) && !filter_var($userDetails['email'], FILTER_VALIDATE_EMAIL)) {
$errmsg_arr[] = "the provided email is not a valid email address";
}
$sqlu = "SELECT username FROM users WHERE username = ?";
if($stmt = $con->myconn->prepare($sqlu)){
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
}
if($stmt->fetch() > 0){
$errmsg_arr[] = "Username already exists!";
$stmt->close();
}
$sqle = "SELECT email FROM users WHERE email = ?";
if($stmt = $con->myconn->prepare($sqle)){
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
}
if($stmt->fetch() > 0){
$errmsg_arr[] = "Email already exists!";
$stmt->close();
}
}
return $errmsg_arr;
}
Everything works perfect. But there's a flaw in this check.
Someone goes to their profile.
The person tries to edit details, edits it all: code echo's "succesfully edited".
But if the person tries to edit Email only instead of all details, gets the error message that the "Username value" already exists.
Now my question: How would I let it not check on the username value if it isn't edited? Or email value?
Thanks in advance!
you would exclude the user that's logged in from the query. While doing the login you would save the users id in a session variable. You can use this variable for preventing the queries from checking against the user itself
$sqlu = "SELECT username FROM users WHERE username = ? AND id != '".$_SESSION['user_id']."'";
$sqle = "SELECT email FROM users WHERE email = ? AND id != '".$_SESSION['user_id']."'";
That should fix your issue! More info on session variables

Making sure that an username doesn't exit already with 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]>");

Categories