-2

I'm trying to check if a user exists on the database using a form front end. If the user is there don't add to the database.

The code isn't working when adding a user it gives me the user has been added even the user exists.

Here my code:

<?php
$connection = mysql_connect("localhost", "dbuser", "dbpasswd"); // Establishing Connection with Server
$db = mysql_select_db("ldap", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$netid = $_POST['netid'];
$univid = $_POST['univid'];
if($netid !=''||$univid !=''){
//Insert Query of SQL
$query = mysql_query("SELECT FROM user ( UserName, temppass WHERE UserName=$netid");

if(mysql_num_rows($sql)>=1)

{
    echo"NetID $netid already exists";
   }
 else
    {
   //insert query goes here
   $query = mysql_query("insert into user( UserName, temppass ) values ('$netid', '$univid')");
    }

echo "<br/><br/><span>User Registered successfully...!!</span>";
}
else{
echo "<p>Registration Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
?>
pirulo
  • 335
  • 1
  • 5
  • 13

2 Answers2

2

You could do something like:

$query = mysql_query("SELECT COUNT(UserName) as total FROM user;"); 

Then

$result = mysql_fetch_assoc($query);

The count of users will be in $result['total']. As an aside the mysql_* methods are inferior to prepared statements (google it).

Nicholas Byfleet
  • 581
  • 3
  • 15
0

Your select query has many errors with it.

SELECT FROM user ( UserName, temppass WHERE UserName=$netid

First issue you aren't selecting anything. Second issue I don't know what ( UserName, temppass is, maybe the columns you want to select? Third issue is that Username is presumably a string, not an integer, so that value should be in quotes. Once you quote that though you will open yourself to SQL injections.

Here is a valid version of your current query.

SELECT UserName, temppass FROM user WHERE UserName='$netid'

Here's the doc on mysql's select: http://dev.mysql.com/doc/refman/5.7/en/select.html

Here are some links to read up on about SQL injections:
How can I prevent SQL injection in PHP?
http://php.net/manual/en/security.database.sql-injection.php

You also shouldn't be using the mysql_ functions they are deprecated and insecure now. Why shouldn't I use mysql_* functions in PHP?

Additional issues:

if(mysql_num_rows($sql)>=1)

The $sql isn't defined.

I don't know what $_POST['netid'] is but that sounds like an id, not a username.

You shouldn't store passwords in plain text.

You should enable error reporting and/or monitor your error logs.

Community
  • 1
  • 1
chris85
  • 23,846
  • 7
  • 34
  • 51
  • I replace the query, but I still cannot get it to work. My form still failing to check if the user already exists. – pirulo Nov 30 '15 at 04:28