Solved

How do I make my php login script work with mysql

Posted on 2009-07-14
34
215 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 18
  • 10
  • 4
  • +1
34 Comments
 
LVL 4

Expert Comment

by:Xemorph
ID: 24856408
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
ID: 24856415
Sorry, mysql_query_db() is mysql_query().  
0
 
LVL 4

Expert Comment

by:Xemorph
ID: 24856425
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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

Author Comment

by:Bulg
ID: 24856475
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
ID: 24857141
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
ID: 24857179
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
ID: 24857757
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
ID: 24857796
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
ID: 24860971
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
ID: 24861261
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
ID: 24861291
What about my solution, doesn't work? It is simple and stream lined as I see it.
0
 

Author Comment

by:Bulg
ID: 24861342
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
ID: 24861406
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
ID: 24861563
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
ID: 24861599
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
ID: 24861654
$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
ID: 24861669
"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
 

Author Comment

by:Bulg
ID: 24861723
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
ID: 24861771
Correct.
0
 
LVL 14

Expert Comment

by:profya
ID: 24861789
do you have a field in your table called firstname?
0
 

Author Comment

by:Bulg
ID: 24861834
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
ID: 24862290
Where are the attachments?
0
 

Author Comment

by:Bulg
ID: 24862331
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
ID: 24862409
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
ID: 24862686
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
ID: 24862709
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
ID: 24862804
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
ID: 24862978
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
ID: 24863013
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
ID: 24863082
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
ID: 24863121
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
ID: 24863203
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
ID: 24863276
OMG thank you for the huge help. its working perfectly.
0
 
LVL 14

Expert Comment

by:profya
ID: 24863333
Thanks you for the points,  You are welcome :)
0

Featured Post

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Difference between PHPClasse.php and SimplXLS.php 5 45
Script to move computer from one domain to another 6 52
Scripting 4 29
php time 12 23
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article will show, step by step, how to integrate R code into a R Sweave document
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

737 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