Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

Need help with Login System (MySQLDB)

Newbie Spellweaver
Joined
May 27, 2013
Messages
18
Reaction score
0
Hello everyone ! Im currently developing a login system with Python and using MySQLDB. Im currently stuck at letting the program access the database and check if the username and password entered by the user matches or no. I googled, youtubed and still cant find any working result.

Current Python Code:
Code:
import MySQLdb

neworold=raw_input("Welcome to the Logon System! Had you got an account? (Y/N): ")
while neworold=="N" or neworold=="n":
   print"Please register an account!"
   username=raw_input("Username: ")
   password=raw_input("Password: ")
   name=raw_input("Real Name: ")
   email=raw_input("Email: ")
   hpnum=raw_input("HP No.: ")
   # Open database connection
   db = MySQLdb.connect("localhost","root","","logon" )
   cursor = db.cursor()
   sql = "INSERT INTO accounts (username, password, name, email, hpnum) \
      VALUES ('%s', '%s', '%s', '%s', '%s' )" % \
      (username, password, name, email, hpnum)
   try:
      cursor.execute(sql)
      db.commit()
   except:
      db.rollback()
   db.close()   
   print"Account Registered!"
   neworold="Y"
print"Please login into your account!"
while neworold=="Y" or neworold=="y":
   username=raw_input("Username: ")
   password=raw_input("Password: ")
   db = MySQLdb.connect("localhost","root","","logon" )
   cursor = db.cursor()
   if cursor.execute("SELECT * FROM `accounts` where `username`= ' " + username + " ' AND `password` =' " + password + " ' "):
      print "Welcome back! "
   else:
      print"Incorrect username or Password"

MySQL Script:

Code:
/*!40101 SET @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;/*!40101 SET @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;


/*!40014 SET @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;






CREATE DATABASE IF NOT EXISTS logon;
USE logon;

--
-- Definition of table `accounts`
--


DROP TABLE IF EXISTS `accounts`;
CREATE TABLE `accounts` (
  `userid` int(11) NOT NULL auto_increment,
  `username` varchar(13) NOT NULL default '',
  `password` varchar(128) NOT NULL default '',
  `name` tinytext,
  `email` tinytext,
  `hpnum` int(11),
  PRIMARY KEY  (`userid`),
  UNIQUE KEY `username` (`username`),
  KEY `userid` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=526 DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC;


/*!40101 SET SQL_MODE @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_COLLATION_CONNECTION */;
/*!40101 SET CHARACTER_SET_CLIENT @[I][B][URL="https://forum.ragezone.com/members/1333464006.html"]old[/URL][/B][/I]_CHARACTER_SET_CLIENT */;
 
Last edited:

Ben

Developer - JS
Developer
Joined
Jul 6, 2013
Messages
1,224
Reaction score
506
Please don't just post and then remove it when you find a solution or used another method to solve the problem, help other members by showing what you did wrong and how you solved it.
 
Newbie Spellweaver
Joined
May 27, 2013
Messages
18
Reaction score
0
Please don't just post and then remove it when you find a solution or used another method to solve the problem, help other members by showing what you did wrong and how you solved it.
Nope, I gave up on it. Nvm, I'll edit back my original post.
If u have solution, feel free to reply also ^^
 
◝(⁰▿⁰)◜Smile◝ (⁰▿⁰)◜
Developer
Joined
May 29, 2007
Messages
2,167
Reaction score
898
You might want to use result = connection.query() and then result.num_rows() > 0.
Basically what you do is when you login, you fetch the row with the corresponding username and password and if the row is found you allow the user to login.

It seems that you just copied some code from somewhere, but the question is: do you understand it?
I never programmed python but I already found out how to use the api properly due to other programming languages.
I suggest checking out the api and trying to understand how to use it.



Enjoy, I'm not going to hold your hand but what I wrote should help you out tough.
 
Newbie Spellweaver
Joined
May 27, 2013
Messages
18
Reaction score
0
You might want to use result = connection.query() and then result.num_rows() > 0.
Basically what you do is when you login, you fetch the row with the corresponding username and password and if the row is found you allow the user to login.

It seems that you just copied some code from somewhere, but the question is: do you understand it?
I never programmed python but I already found out how to use the api properly due to other programming languages.
I suggest checking out the api and trying to understand how to use it.



Enjoy, I'm not going to hold your hand but what I wrote should help you out tough.

Well for the SQL part, yeah, I kinda copied from some sort of example. I never learnt any programming language before and for Python, I was just taught the basic of it. However, my lecturer somehow request us to code a system which the codings are way advanced than what she taught and I have only 1 week to do it. Deadline is on Friday. So I can't really have the skill to fully understand the codes now but for the codes I copied & wrote, I felt it's logical but no idea why it's not working.

Due to lack of time, knowledge and guidance, I already plan to give up this project and ready to get 0 marks for it. Lol
 

Ben

Developer - JS
Developer
Joined
Jul 6, 2013
Messages
1,224
Reaction score
506
Well for the SQL part, yeah, I kinda copied from some sort of example. I never learnt any programming language before and for Python, I was just taught the basic of it. However, my lecturer somehow request us to code a system which the codings are way advanced than what she taught and I have only 1 week to do it. Deadline is on Friday. So I can't really have the skill to fully understand the codes now but for the codes I copied & wrote, I felt it's logical but no idea why it's not working.

Due to lack of time, knowledge and guidance, I already plan to give up this project and ready to get 0 marks for it. Lol

You could check php code and see if you find something there, i found a full php script earlier that was with register and login..

Maybe that will help you on python.
 
Experienced Elementalist
Joined
May 6, 2008
Messages
230
Reaction score
52
The main problem I see is that your not fetching the result in your query so your not returning a result. Use a command like fetchall(). Anyways here is one I wrote up really quick based off of yours above. Try to study it a bit so you can understand how everything is being executed.
Code:
#Lets import our mysql functions for python
import  MySQLdb

#Lets attempt to login to mysql
try:
    #Mysql Connection and Controller
    db = MySQLdb.connect(user='root', passwd='', host='localhost', db='logon')
#Make sure we don't have any connection problems
except MySQLdb.Error as err:
    print(err)
    exit()

#MySql Database cursor / input
cursor = db.cursor()

#prompt the user for Account availability
neworold = raw_input("Welcome to the Login System! Do you have an account? (Y/N): ")

#If there is no account, then we will make one
if(neworold.upper() == "N") :
    print("Please register your account!")
    #Lets gather some Account Information
    userid = raw_input("UserID: ")
    password = raw_input("Password: ")
    name = raw_input("Real Name: ")
    email = raw_input("Email: ")
    hpnum = raw_input("HP No.: ")
    #Now lets try to insert this into our MySql Database
    try:
        #Prepare and execute our query
        cursor.execute("INSERT INTO accounts (username, password, name, email, hpnum) "
                       "VALUES (%s, %s, %s, %s, %s )" , (userid, password, name, email, hpnum))
        #commit changes to database
        db.commit()
        #Close MySql Connection
        db.close()
        #Make sure everything went smooth between python and MySql
    except MySQLdb.Error as err:
        print(err)
        #Undo any changes made by our query
        db.rollback()
        #close our MySql Connection
        db.close()
        #Exit Application
        exit()

    #Success!
    print("Account Registered! Welcome, %s" % userid)

else:
    #Request Login Information
    print("Please Login!")
    userid = raw_input("UserID: ")
    password = raw_input("Password: ")
    #  Lets try to Login to the account
    try:
        #Prepare and execute our query
        cursor.execute("SELECT * FROM accounts WHERE username = %s AND password = %s" , (userid, password))
        #Grab the returned data from the query
        cursor.fetchall()
        #Close our MySql Connection
        db.close()
        #Check to make sure our query found a result / row with our data
        if(cursor.rowcount != 1):
            print("Invalid UserID or Password!")
            #Exit Application
            exit()

    #Make sure everything went smooth between python and MySql
    except MySQLdb.Error as err:
        #Display error from MySql
        print(err)
        #Exit Application
        exit()

    #Sucess!
    print("Welcome back, %s" % userid)
 
Last edited:
Newbie Spellweaver
Joined
May 27, 2013
Messages
18
Reaction score
0
The main problem I see is that your not fetching the result in your query so your not returning a result. Use a command like fetchall(). Anyways here is one I wrote up really quick based off of yours above. Try to study it a bit so you can understand how everything is being executed.
Code:
#Lets import our mysql functions for python
import  MySQLdb

#Lets attempt to login to mysql
try:
    #Mysql Connection and Controller
    db = MySQLdb.connect(user='root', passwd='', host='localhost', db='logon')
#Make sure we don't have any connection problems
except MySQLdb.Error as err:
    print(err)
    exit()

#MySql Database cursor / input
cursor = db.cursor()

#prompt the user for Account availability
neworold = raw_input("Welcome to the Login System! Do you have an account? (Y/N): ")

#If there is no account, then we will make one
if(neworold.upper() == "N") :
    print("Please register your account!")
    #Lets gather some Account Information
    userid = raw_input("UserID: ")
    password = raw_input("Password: ")
    name = raw_input("Real Name: ")
    email = raw_input("Email: ")
    hpnum = raw_input("HP No.: ")
    #Now lets try to insert this into our MySql Database
    try:
        #Prepare and execute our query
        cursor.execute("INSERT INTO accounts (username, password, name, email, hpnum) "
                       "VALUES (%s, %s, %s, %s, %s )" , (userid, password, name, email, hpnum))
        #commit changes to database
        db.commit()
        #Close MySql Connection
        db.close()
        #Make sure everything went smooth between python and MySql
    except MySQLdb.Error as err:
        print(err)
        #Undo any changes made by our query
        db.rollback()
        #close our MySql Connection
        db.close()
        #Exit Application
        exit()

    #Success!
    print("Account Registered! Welcome, %s" % userid)

else:
    #Request Login Information
    print("Please Login!")
    userid = raw_input("UserID: ")
    password = raw_input("Password: ")
    #  Lets try to Login to the account
    try:
        #Prepare and execute our query
        cursor.execute("SELECT * FROM accounts WHERE username = %s AND password = %s" , (userid, password))
        #Grab the returned data from the query
        cursor.fetchall()
        #Close our MySql Connection
        db.close()
        #Check to make sure our query found a result / row with our data
        if(cursor.rowcount != 1):
            print("Invalid UserID or Password!")
            #Exit Application
            exit()

    #Make sure everything went smooth between python and MySql
    except MySQLdb.Error as err:
        #Display error from MySql
        print(err)
        #Exit Application
        exit()

    #Sucess!
    print("Welcome back, %s" % userid)

Holy poop! Thanks dude. So it needs to try: .....
 
Experienced Elementalist
Joined
May 6, 2008
Messages
230
Reaction score
52
The try: is only there to catch an error and exit if one occurs. All try: does is monitor the statements and handle exceptions in the matter you have defined under "catch message"

cursor.fetchall() actually runs the query in cursor.execute() and reads back the result to cursor mem, while db.commit() in the previous runs the query in cursor.execute() and commits a change to the database instead of just storing it.
 
Last edited:
Back
Top