How do I make my php login script work with mysql

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
BulgAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

XemorphCommented:
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
XemorphCommented:
Sorry, mysql_query_db() is mysql_query().  
0
XemorphCommented:
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
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

BulgAuthor Commented:
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
racmail2001Commented:
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
racmail2001Commented:
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
profyaCommented:
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
profyaCommented:
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
XemorphCommented:
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
BulgAuthor Commented:
after putting this "<br>$sql<br>"; on line 13 nothing really changes i get the same message as before. wrong nick or password
0
profyaCommented:
What about my solution, doesn't work? It is simple and stream lined as I see it.
0
BulgAuthor Commented:
i even tryed the code profya: said to use and it still tells me Invalid Username or Password
0
profyaCommented:
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
BulgAuthor Commented:
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
profyaCommented:
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
profyaCommented:
$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
profyaCommented:
"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
BulgAuthor Commented:
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
profyaCommented:
Correct.
0
profyaCommented:
do you have a field in your table called firstname?
0
BulgAuthor Commented:
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
profyaCommented:
Where are the attachments?
0
BulgAuthor Commented:
its all the way up in my original question post its a screenshot of how my table looks in phpmyadmin hope it helps
0
profyaCommented:
I'll reproduce it right now and give the complete running code. No problem.
0
profyaCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
profyaCommented:
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
profyaCommented:
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
BulgAuthor Commented:
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
profyaCommented:
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
profyaCommented:
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
BulgAuthor Commented:
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
profyaCommented:
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
BulgAuthor Commented:
OMG thank you for the huge help. its working perfectly.
0
profyaCommented:
Thanks you for the points,  You are welcome :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.