Question

I have been trying to figure this out for hours but haven't succeeded. I'm making a registration page in PHP for a MSSQL Database. I figured out how to insert the username in the database, however I'm not sure how to check if it exists. Here's my code:

<?php
$server = "----";
$user = "----";
$pass = "----";
$db = "----";

$link = mssql_connect($server, $user, $pass);
$selected = mssql_select_db ($db, $link);
?>

--------------------------------   

<html>
<head>
</head>
<body>
<center>
<form action="register.php" method="post">
<div style="border: 1px solid black; width:320px; font-family:arial;">
<center>
<table cellspacing="5">
<tr>
<td>Account:</td><td><input type="text" name="username" value="" /></td>
</tr>
<tr>
<td>Password:</td><td><input type="text" name="password" value="" /></td>
</tr>
<tr>
<td colspan="2"><center><input type="submit" value="submit" /></center></td>
</tr>
</table>
</center>
</div>
</form>
</center>
</body>
</html>

-------------------------------- 

<?php
require_once('config.php');
$username=$_POST['username'];
$password=$_POST['password'];
$query = "INSERT INTO Accounts (AccountName, Password) VALUES ('$username', '$password')"; 
//if username exists {}
//else {
$result = mssql_query($query);
// }
?>
Was it helpful?

Solution

Consult the following using the mssql_num_rows() function.

$query_check = "SELECT * FROM Accounts WHERE AccountName='$username' AND Password='$password'";
$results = mssql_query($query_check);

if(mssql_num_rows($results) > 0){
  echo "Exists.";
}

else{
  echo "Sorry.";
}

Plus I suggest you change:

<input type="text" name="password" value="" />

to

<input type="password" name="password" value="" />

as you will be exposing passwords in plain viewable text.


You're presently open to SQL injection.

You should be using bound parameters.

Read the following articles:


Passwords

I noticed that you may be storing passwords in plain text. This is not recommended.

Consider using one of the following:

Other links:

OTHER TIPS

do like following. your password might be in encrypted format so you have to check accordingly

$sql="SELECT * FROM Accounts WHERE AccountName='$username' AND Password='$password'";
$result = mssql_query($sql);
if (mssql_num_rows($query)) {
  echo 'user exists';
}else{
  echo 'user does not exist';
}
  1. use @parameter to pass the value to the stored procedure

  2. to find the username already exits

Write a stored procedure

create stored procedure abc
    @username varchar(20),
    @pass varchar(20)

    if exists(select usename 
              from tablename 
              where username = @username and password = @pass)
    begin
        select 
            'alreadyexists' as result
    end
    else
    begin
        select usename  
        from tablename 
        where username = @username and password = @pass
    end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top