Checking User Name or User Email Already Exists

checking user name or user email already exists

Like I said in my comment your design is bad !

First you should have Data Access Layer. This should be project in big solutions but in your case you can put it like new directory. In this directory you create SqlManager class here is the code:

public class SqlManager
{

public static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["DevConnString"].ConnectionString;
}
}

public static SqlConnection GetSqlConnection(SqlCommand cmd)
{
if (cmd.Connection == null)
{
SqlConnection conn = new SqlConnection(ConnectionString);

conn.Open();

cmd.Connection = conn;

return conn;
}

return cmd.Connection;
}

public static int ExecuteNonQuery(SqlCommand cmd)
{
SqlConnection conn = GetSqlConnection(cmd);

try
{
return cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}

public static object ExecuteScalar(SqlCommand cmd)
{

SqlConnection conn = GetSqlConnection(cmd);

try
{
return cmd.ExecuteScalar();
}
catch
{
throw;
}
finally
{
conn.Close();
}
}

public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}

public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);

try
{
DataSet resultDst = new DataSet();

using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}

return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}

public static DataRow GetDataRow(SqlCommand cmd)
{
return GetDataRow(cmd, "Table");
}

public static DataRow GetDataRow(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);

try
{
DataSet resultDst = new DataSet();

using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}

if (resultDst.Tables.Count > 0 && resultDst.Tables[0].Rows.Count > 0)
{
return resultDst.Tables[0].Rows[0];
}
else
{
return null;
}
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
}

After that you should have Business Object Layer. In bigger solution is project in your case directory. If you are in the page TaxesEdit.aspx, you should add Tax.cs class in the BO(business object).

Example of methods for the class, for your first button:

public DataSet GetTaxesByUserName(string userName)
{
SqlCommand cmd = new SqlCommand(@"

select 1 from Table where Name =@UserName");

cmd.Parameters.AddWithValue("@UserName", userName);

return DA.SqlManager.GetDataSet(cmd);
}

You fetch all the needed data in datasets. After that you make checks like taxesDst.Tables[0].Rows.Count > 0 (or == 0)

For Insert you can have method like this:

    public virtual void Insert(params object[] colValues)
{
if (colValues == null || colValues.Length % 2 != 0)
throw new ArgumentException("Invalid column values passed in. Expects pairs (ColumnName, ColumnValue).");

SqlCommand cmd = new SqlCommand("INSERT INTO " + TableName + " ( {0} ) VALUES ( {1} )");

string insertCols = string.Empty;
string insertParams = string.Empty;

for (int i = 0; i < colValues.Length; i += 2)
{
string separator = ", ";
if (i == colValues.Length - 2)
separator = "";

string param = "@P" + i;

insertCols += colValues[i] + separator;
insertParams += param + separator;

cmd.Parameters.AddWithValue(param, colValues[i + 1]);
}

cmd.CommandText = string.Format(cmd.CommandText, insertCols, insertParams);

DA.SqlManager.ExecuteNonQuery(cmd);
}

For this you need to have property TableName in the current BO class.

In this case this methods can be used everywhere and you need only one line of code to invoke them and no problems like yours will happen.

check if username and email already exists in database

First of all, session_start() is called 2 times.
Remove the repeated call inside if ($password == $password2) {
You code is also missing a ; and some } (for properly closing your if conditions)

Now the solution:
Before you can process Database query's result, you need to connect to a DB and execute appropriate SQL command, only then you will get the result you want. Your code is missing this process.

Check my comments in your code below↓ and then check again in corrected code

if ($password == $password2) {
session_start(); // remove this repeated call
$password = ($password);
$sql="select * from account_info where (username='$username' or email='$email')";
if (mysqli_num_rows($res) > 0) { // $res isn't defined
$row = mysqli_fetch_assoc($res);
if ($username==$row['username'])
{
$_SESSION['message'] = "Username je vec registrovan";
}
else($email==$row['email']){ // `else` doesn't work this way, use `elseif`
$_SESSION['message'] = "Email je vec registrovan" // ; missing
}


Corrected Code:

if (isset($_POST['register_btn'])) {
$name = mysqli_real_escape_string($db, $_POST['name']);
$lastname = mysqli_real_escape_string($db, $_POST['lastname']);
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$password2 = mysqli_real_escape_string($db, $_POST['password2']);

if ($password == $password2) {
$password = ($password);
$sql = "SELECT * FROM users WHERE (username='$username' OR email='$email')";
$res = mysqli_query($db, $sql); // you were calling $res but it wasn't defined; this connects to the DB and executes SQL and then assigns the result
if (mysqli_num_rows($res) > 0) {
$row = mysqli_fetch_assoc($res);
if ($username == $row['username']) {
$_SESSION['message'] = "Username je vec registrovan";
} elseif ($email == $row['email']) { // changed `else` to `elseif` to include the condition, `else` doesn't accept conditional checks
$_SESSION['message'] = "Email je vec registrovan"; // added ;
}
} else {
$sql = "INSERT INTO users (name, lastname, username, email, password) VALUES ('$name', '$lastname', '$username', '$email', '$password')";
if (mysqli_query($db, $sql)) {
// New record inserted
$_SESSION['message'] = "Sada si ulogovan";
$_SESSION['message'] = $username;
header("location: login.php");
} else {
echo("Error: " . mysqli_error($db));
}
}
} // required to close the password checking condition
else {
$_SESSION['message'] = "Ne podudaraju se lozinke!";
}
}

Suggestions:

  1. Use prepared statement instead of directly passing user provided input into SQL
    (critical, your current code is vulnerable to SQL injection)
  2. Use an IDE that supports PHP and offers syntax highlighting (Atom, Visual Studio Code, PhpStorm etc.)

check if username and email already exists with expressjs validator and mysql

This code works for me:

const express = require('express');
const router = express.Router();
const { check,validationResult } = require('express-validator');
const bcrypt = require('bcrypt');
const bcryptRounds = 10;

router.post('/register', [
check('username')
.exists()
.trim()
.matches(/^[a-zA-Z\ö\ç\ş\ı\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü ]{3,16}$/)
.withMessage('Invalid username!'),
check('mentionName')
.exists()
.trim()
.matches(/^(?=.*[a-z])[a-z0-9_]{3,15}$/)
.custom(async mentionName => {
const value = await isMentionNameInUse(mentionName);
if (value) {
throw new Error('Mention name is already exists!!!');
}
})
.withMessage('Invalid mention name!!!'),
check('email')
.exists()
.isLength({ min: 6, max: 100 })
.isEmail()
.normalizeEmail()
.trim()
.custom(async email => {
const value = await isEmailInUse(email);
if (value) {
throw new Error('Email is already exists!!!');
}
})
.withMessage('Invalid email address!!!'),
check('password')
.exists()
.isLength({ min: 6, max: 16 })
.escape()
.trim()
.withMessage('Invalid password!!!'),
check('rePassword').exists().custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('The passwords is not same!!!');
}
return true;
})
],
function (req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
} else {
console.log("----->START USER REGISTRATION");
const username = req.body.username;
const mentionName = '@'+req.body.mentionName;
const email = req.body.email;
const pass = req.body.password;
bcrypt.hash(pass, bcryptRounds, function(err, hash) {
console.log("HASH PASS : "+hash);
//INSERT USER
});
}
});

function isMentionNameInUse(mentionName){
var conn = require('../../modules/mysql_db');
return new Promise((resolve, reject) => {
conn.query('SELECT COUNT(*) AS total FROM users_table WHERE m_name = ?', [mentionName], function (error, results, fields) {
if(!error){
console.log("MENTION COUNT : "+results[0].total);
return resolve(results[0].total > 0);
} else {
return reject(new Error('Database error!!'));
}
}
);
});
}

function isEmailInUse(email){
var conn = require('../../modules/mysql_db');
return new Promise((resolve, reject) => {
conn.query('SELECT COUNT(*) AS total FROM users_table WHERE email = ?', [email], function (error, results, fields) {
if(!error){
console.log("EMAIL COUNT : "+results[0].total);
return resolve(results[0].total > 0);
} else {
return reject(new Error('Database error!!'));
}
}
);
});
}


Related Topics



Leave a reply



Submit