Solved

How do I make my php login script work with mysql

Posted on 2009-07-14
34
210 Views
Last Modified: 2013-12-13
hello, i am trying to make a login script. i tryed making it by looking at examples but now i am lost and cant understand whats wrong. What can i change in my code to make it work i have en error Warning: mysql_num_rows(): supplied argument is not a valid
My table is different from the example i got some of the code from.I think that could be the problem. i dont totaly understand the rows code i have attacked a SS of how my table looks like from myphpadmin. i hope the info provided is helpfull. thank you for the help in advens.
<?php

$host="localhost";

$username="";

$password="";

$db_name="";

$tbl_name="";

mysql_connect("$host", "$username", "$password")or die("cannot connect");

mysql_select_db("$db_name")or die("cannot select DB");

$nickname=$_POST['nickname'];

$password=$_POST['password']; 

$count=mysql_num_rows($result);

if($count==1){

session_register("nickname");

session_register("password");

header("location:login_success.php");

}

else {

echo "Wrong Username or Password";

}

?>

Open in new window

database.bmp
0
Comment
Question by:Bulg
  • 18
  • 10
  • 4
  • +1
34 Comments
 
LVL 4

Expert Comment

by:Xemorph
Comment Utility
You forgot to query the database.  Looks like you got the connect and selecting db right, but you need to do an sql query.

When you do this, it will return a mysql results.  This is what you pass into mysql_num_rows();

There are some other issues, like you do not have an index defined (slow searches).  Hope this helps
<?php

$host="localhost";

$username="";

$password="";

$db_name="";

$tbl_name="";

mysql_connect("$host", "$username", "$password")or die("cannot connect");

mysql_select_db("$db_name")or die("cannot select DB");

$nickname=$_POST['nickname'];

$password=$_POST['password']; 
 

// ADD THIS------------------------

$sql = "SELECT firstname FROM members 

        WHERE nickname='".mysql_real_escape_string($nickname)."' 

            AND password='".mysql_real_escape_string($password)."'";
 

$results = mysql_query_db($sql);
 

$count=mysql_num_rows($results);
 

//------------------------------------
 

if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
 

// Change  This

session_register("nickname");

session_register("password");
 

// TO THIS

$row = mysql_fetch_assoc($results);

$_SESSION['nickname'] = $row['nickname'];

$_SESSION['password'] = $row['password'];
 

header("location:login_success.php");

}

else {

echo "Wrong Username or Password";

}

?>

Open in new window

0
 
LVL 4

Expert Comment

by:Xemorph
Comment Utility
Sorry, mysql_query_db() is mysql_query().  
0
 
LVL 4

Expert Comment

by:Xemorph
Comment Utility
I would also recommend finding a mysql tutorial.  This will help you grasp how the flow of things should happen, and what is really going on.

Just google search for "mysql tutorials".
0
 

Author Comment

by:Bulg
Comment Utility
ok now it shows me Wrong Username or Password
this is how my code should look like correct?
i only changed this line $sql = "SELECT firstname FROM members    changed members to form cuz that is the name of the table i am getting the info from.
i double checked the password and name from the batabase and it correct any ideas what could be wrong?
$tbl_name="form";

mysql_connect("$host", "$username", "$password")or die("cannot connect");

mysql_select_db("$db_name")or die("cannot select DB");

$nickname=$_POST['nickname'];

$password=$_POST['password']; 

$sql = "SELECT firstname FROM form 

        WHERE nickname='".mysql_real_escape_string($nickname)."' 

            AND password='".mysql_real_escape_string($password)."'";

 

$results = mysql_query($sql);

 

$count=mysql_num_rows($results);
 

if($count==1){

$row = mysql_fetch_assoc($results);

$_SESSION['nickname'] = $row['nickname'];

$_SESSION['password'] = $row['password'];

header("location:login_success.php");

}

else {

echo "Wrong Username or Password";

}

?>

Open in new window

0
 
LVL 10

Expert Comment

by:racmail2001
Comment Utility
try to insert on line 13 the following line:
echo "<br>$sql<br>";

and after trying again the sql will be printed on the screen

try to copy the sql and run it in phpmyadmin and see if you can get a result

maybe form showing the query on the screen you can spot the problem also
0
 
LVL 10

Expert Comment

by:racmail2001
Comment Utility
it can be a problem with the form where you get your data from.

for this reason in development stage it's best to use this debug technics.

like this you can spot your problem in no time
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
Try this:
<?php

$host="localhost";

$username="";

$password="";

$db_name="";

$tbl_name="";

mysql_connect("$host", "$username", "$password")or die("cannot connect");

mysql_select_db("$db_name")or die("cannot select DB");

$nickname=@$_POST['nickname'];

$password=@$_POST['password']; 

 

$sql = "SELECT firstname, nickname, password FROM members WHERE nickname='".mysql_real_escape_string($nickname)."' AND password='".mysql_real_escape_string($password)."'";

$rs = mysql_query($sql);

if ($rs && mysql_num_rows($rs)>0 && $rec=mysql_fetch_array($rs))

{

	session_start();

	$_SESSION['authentiated']=true;

	$_SESSION['firstname']=$rec['firstname'];

	$_SESSION['nickname']=$rec['nickname'];

	$_SESSION['password']=sha1($rec['password']."_|!");//Cache password hashed, for later change password

	header("location:login_success.php");

}

else {

	echo "Invalid Username or Password";

}

?>

Open in new window

0
 
LVL 14

Expert Comment

by:profya
Comment Utility
My solution does:
1) Connect and query the database.
2) If there is one record it starts session and save variables to the session and redirect the user to the next page.
3) It saves the password hashed, for example if you want to let the user change the password and you want to ask him/her about the old password you can check it with something like:
SELECT * FROM memebers WHERE CONCAT(SHA1(password), '_|!')=".$_SESSION['password'];

4) It saves a flag to tell you whether the user has been authenticated or not. Your application rest of the the pages can run this code at the begining of the page:
session_start();
if ($_SESSION['authenticated']!=true)
header("location: loginpage.php");

I hope this helps
0
 
LVL 4

Expert Comment

by:Xemorph
Comment Utility
I would do what racmail said.

Your post variables might not be getting set.  Printing out the sql will help us see what might be causing the issue.
0
 

Author Comment

by:Bulg
Comment Utility
after putting this "<br>$sql<br>"; on line 13 nothing really changes i get the same message as before. wrong nick or password
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
What about my solution, doesn't work? It is simple and stream lined as I see it.
0
 

Author Comment

by:Bulg
Comment Utility
i even tryed the code profya: said to use and it still tells me Invalid Username or Password
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
There are few reasons for this, we can figure it out by these echos:
echo $sql;
echo mysql_num_rows($rs);
echo mysql_error();

May be there is a problem with the query, may be there is not name and password as we have specified, the password may be hashed using password or md5 functions.

Please run these echos and feed us back.
0
 

Author Comment

by:Bulg
Comment Utility
Invalid Username or PasswordSELECT firstname, nickname, password FROM members WHERE nickname='' AND password=''
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in checklogin.php on line 33
Unknown column 'firstname' in 'field list'
i asked this before but didnt get answer in on line 12 $sql = "SELECT firstname, nickname, password FROM members WHERE nickname='"    in this code should i change members to form witch is the name of my table? if i do that i only get this message  
Invalid Username or PasswordSELECT firstname, nickname, password FROM form WHERE nickname='' AND password=''0
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
Yes, you need to change members to the real table name you are using to hold users info. Another thing, as you can see in the WHERE clause, both nickname and password are empty. This means that the $variables are also empty.
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
$nickname and $password are empty, does the input in the login form are named nickname for user name and password for the password?

Those variable empty because either they are referencing wrong input names, or the login form is not using POST, rather it is using GET. Check the login form method.
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
"i asked this before but didnt get answer in on line 12"
regardless everything, I'll work with you until this simple problem fixed. :)
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:Bulg
Comment Utility
yea i asked the other user about it cuz i wasnt sure if it should stay like that or i should have changed it. dont wantt to mess it up or leave something out ::(
i think i did the form right is this how it should look like?
<form id='loginform' action='../checklogin.php' method="POST">

<fieldset>

        <legend></legend> 

         

        <div class="lbl">

          <label for="nickname">Username:&nbsp;&nbsp;</label>

        </div>
 

        <div class="npt">

          <input type="text" id="nickname" />

        </div>

        <div class="lbl">
 

          <label for="password">Password:&nbsp;&nbsp;</label>

        </div>
 

        <div class="npt">

          <input type="password" id="password" />

        </div>

        <div class="npt1">

         <input type="submit" value="Log In" />

        </div>
 

   

      </fieldset>

    </form>

Open in new window

0
 
LVL 14

Expert Comment

by:profya
Comment Utility
Correct.
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
do you have a field in your table called firstname?
0
 

Author Comment

by:Bulg
Comment Utility
yes sir i believe i do. i have attached a screenshot of my table with all the fields. i also have no index defined could that be the problem?
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
Where are the attachments?
0
 

Author Comment

by:Bulg
Comment Utility
its all the way up in my original question post its a screenshot of how my table looks in phpmyadmin hope it helps
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
I'll reproduce it right now and give the complete running code. No problem.
0
 
LVL 14

Accepted Solution

by:
profya earned 500 total points
Comment Utility
I got it, in the login form you missed to name inputs, you only specified the id, as you know, forms use input names to pass values. The following code is 100% working:
Login Form:

<form	id='loginform' action='../checklogin.php' method="POST">

        <legend></legend>
 

        <div class="lbl">

          <label for="nickname">Username:  </label>

        </div>
 

        <div class="npt">

          <input type="text" name="nickname" />

        </div>

        <div class="lbl">
 

          <label for="password">Password:  </label>

        </div>
 

        <div class="npt">

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

        </div>

        <div class="npt1">

         <input type="submit" value="Log In" />

        </div>
 
 

      </fieldset>

    </form>
 
 

Check Login:

<?php

$host="localhost";

$username="root";

$password="";

$db_name="clashg5_mainform";

$tbl_name="form";

mysql_connect("$host", "$username", "$password")or die("cannot connect");

mysql_select_db("$db_name")or die("cannot select DB");

$nickname=$_POST['nickname'];

$password=$_POST['password'];

$sql = "SELECT firstname, nickname, password FROM ".$tbl_name." WHERE nickname='".mysql_real_escape_string($nickname)."' AND password='".mysql_real_escape_string($password)."'";

$rs = mysql_query($sql);

echo mysql_error();

if ($rs && mysql_num_rows($rs)>0 && $rec=mysql_fetch_array($rs))

{

        session_start();

        $_SESSION['authentiated']=true;

        $_SESSION['firstname']=$rec['firstname'];

        $_SESSION['nickname']=$rec['nickname'];

        $_SESSION['password']=sha1($rec['password']."_|!");//Cache password hashed, for later change password

        header("location:login_success.php");

}

else {

        echo "Invalid Username or Password";

}

?>

Open in new window

0
 
LVL 14

Expert Comment

by:profya
Comment Utility
The page: login_success.php is the page where user goes to when login is successful.
Your problem introduced me to a real madness, I submit the login form I got nothing in the checklogin.php page!!!!!!!! I lost my mind on that man.
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
Now it is time for advancements:
1) You have to change your table data type from text to varchar(255) for example. Because text data type used when data length is undetermined, for long text such as articles and stories. It consumes much more server resources. It is highly recommended to avoid it as much as possible.
2) You have to create the primary key. In theory each table should have a primary key, the field that Identifies each row in the table. It enhances updating and deleting records and it also accelerates select statements.
3) Use appropriate width for your textual fields, for example the password should not exceed 32 chars max.
4) You should add a unique index for the nickname field, because you use it to identify users.

I hope this useful and good luck, I am so happy to provide help, that's why EE exists.
:)
0
 

Author Comment

by:Bulg
Comment Utility
ok now i have more problems... omg when is it going to end :P sorry for the madness but its still going :P
now i get all this

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/clashg5/public_html/checklogin.php:5) in /home/clashg5/public_html/checklogin.php on line 23

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/clashg5/public_html/checklogin.php:5) in /home/clashg5/public_html/checklogin.php on line 23

Warning: Cannot modify header information - headers already sent by (output started at /home/clashg5/public_html/checklogin.php:5) in /home/clashg5/public_html/checklogin.php on line 28
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
Yes, before session_start() and header statements, there should be no active echo or print statement. Remove echo mysql_error(); and remove any other echo or print statements or even normal text on the top of the page.
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
With the code I have submitted, I encounter no problem, even echo mysql_error() does not affect the application because there was no database errors. Make sure that your page does not send any character even to the browser before session_start() and header statements.
0
 

Author Comment

by:Bulg
Comment Utility
yea i put it on top now i only get this error
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/clashg5/public_html/login_success.php:5) in /home/clashg5/public_html/login_success.php on line 106
witch is from my login_success.php page the only php code i have is this code the witch i had from the start.
<?

session_start();

if(!session_is_registered(nickname)){

header("location:main_login.php");

}

?>

Open in new window

0
 
LVL 14

Expert Comment

by:profya
Comment Utility
No, login_success.php this is the page where you show to the user when he or she successfully log in.
The login form should be placed on a page named for example login.php, and you have the checklogin.php page to do user authentication. You should have three pages, the login page, the authentication page and the final page when the user has been authenticated.

In the first line of the login successful page:
<?php
session_start();
if ($_SESSION['authenticated']!=1)
header("location: main_login.php");
exit;
?>
There must be no line before that code, even an empty line.
0
 

Author Comment

by:Bulg
Comment Utility
OMG thank you for the huge help. its working perfectly.
0
 
LVL 14

Expert Comment

by:profya
Comment Utility
Thanks you for the points,  You are welcome :)
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Batch, VBS, and scripts in general are incredibly useful for repetitive tasks.  Some tasks can take a while to complete and it can be annoying to check back only to discover that your script finished 5 minutes ago.  Some scripts may complete nearly …
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now