In today's video tutorial, we'll be building a login system with PHP and MYSQL. Many, many features will be covered; including MySqli, Prepared Statements, jQuery, Classes, Sessions, Cookies, etc. I bit off more than I could chew for today's screencast. So, I'll be creating a Part 2 in the next couple of weeks in order to improve our system even further.
Finished! ....For Now
We've managed to get an enormous amount of work done in about forty-five minutes; but there's much room for improvement - specifically when it comes to optimizing our class files for reuse. Before I let you go, let's take a quick look at what we'd like to accomplish in Part 2.
What We Need to Accomplish in a Future Tutorial
- Set an expiration date after creating a session - so that the user is automatically logged off after X minutes.
- Allow users to sign up and edit their passwords.
- Update our database to contain "secret question/answer" questions for username/password retrieval.
- Refactor our class files. As I mentioned in the video tut, there are a few procedures that we should remove from our methods in order to promote "best practices", and increase reusability as much as possible.
- Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.
Related Posts
Check out some more great tutorials and articles that you might like
Plus Members
Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.











User Comments
( ADD YOURS )mamjed January 29th
this is nice! i really wanted to learn how to do this!
( )Fausto Carrera January 29th
Cool stuff, what about a brute force protection, like vanishing the user according with the ip for 20 minutes if the password it’s wrong and he tried more than 5 times?
( )Webmasterish January 29th
Can’t wait for Part 2!
( )Nokadota January 29th
This was helpful, I can’t wait to see the followup tutorial.
( )insic January 29th
very nice tutorial. and you covered prepared statements. awesome!
( )jiang guang liang March 16th
YOU VERY BEANTALFUL
( )Fatihcan April 4th
test sub
David Singer January 29th
Prepared statements are great. PDO is better though
( )Brenelz January 29th
Wow… this tutorial covered a lot.
Do you guys always used prepared statements or every use the standard:
$query = “”;
( )mysql_query($query);
Jeffrey Way January 29th
@Brenelz – It’s not always appropriate to use prepared statements. Sometimes, it can actually be MORE taxing.
But more than anything, prepared statements greatly reduce the risk of SQL injection.
Also why use mysql when you can use mysqli? Still using PHP4?
( )art January 29th
thanx very much! I’ve just start creating login system for one of my sites
( )Ariyo January 29th
Jeff, You simply ROCK! I’m looking forward to the followup tutorial. Thank you so much for doing this.
( )Keith Walter January 29th
Jeff,
( )I had the same problem with Dreamweaver entering the tag when going to a new line. It’s because you’re holding down shift when pressing enter. + is the shortcut for entering a tag. Took me a little while to realize what I was doing, but learning a new shortcut is always a good thing.
Brenelz January 29th
@Jeffery Way
Loved that you took an OO approach to this. I have a good knowledge of how to create classes in PHP but find it tough sometimes to write code so generic. For a programmer like me… Code re-use means making more money!
BTW, That JavaScript in Dreamweaver is awful, and I don’t have a solution. Hopefully someone knows why… :p
( )Keith Walter January 29th
Sorry, I meant break tag, I entered an actual tag forgetting it would take.
( )Pedramphp January 30th
That Was Great I wonder If we had couple of sessions created in the system , and we wanted to remove one of them so we session_destroy , we destroy it no problem but what about the Cookie which You set that to the past , is this cookie for all of our sessions or for a specific one .
( )I’m just confused
Barttos January 30th
Hey, Jeff, thanks for another great screencast! Waiting for part 2! Good luck.
( )Yab January 30th
Hi, i thought about this php/dreamweaver weird curly braces behavior, and maybe that’s because dreamweaver is expecting you to use the following syntax :
if ( a==b)
{
do stuff;
}
Instead of putting your curly brace on the same line as your if statement. I know it's thechnically the same thing, but that would explain the dreamweaver behavior :
if dw sees an open curly brace with this syntax, it'll put the closing brace one indent lower.
( )Yab January 30th
damn, whitespace not showing
( )if ( a==b)
{
do stuff;
}
Jash Sayani January 30th
Wow! Another Login system. I love login systems! BTW, you should also add the conversion of string to SHA1 checksum and store it in the SQL database and then verify the login password with the SHA1 checksum.
( )Jon Keating January 30th
Building an authentication system for a website is generally overlooked as just getting a password attached to the username. Then most developers realize a need for what to do in the case of a forgotten password and implement that. And maybe protect this with a secret question/answer that can be set up. Then perhaps they worry about brute force attacks, and try to devise a way to implement some more security.
In the end, there will be any security issues that need to be decided at each point. For example, with the forgotten password area… Should a new password be e-mail to the user in plain text or should they just be able to reset their password? Can users edit their secret question/answer?
Then there is the issue of protecting your users against phishing attacks.
What I’m trying to say is that, even for a “simple” website, it is quite demanding to be a responsible website and protect the user from abuse. By implementing OpenID, they will source out the authentication system to a provider that has experience with these issues and provide multiple proven methods to protect their users. I think it would be very worthwhile for anyone interested in a login system to consider the advantages of using OpenID.
( )Drew January 30th
I would like to have access to the top secret launch codes if it is not too much to ask Jeff. Thanks much!
( )Mike January 30th
Great tut! I would like to see in the future the use of MySQLi (more extensive) because you use a lot this and to many people only know the classic method.
Thanks for you tutorials!
( )Dennis Lembrechts January 30th
Looking forwards for the other part ! Good job !
( )Suciu Vlad January 30th
maybe u could add ajax to the login system.
( )Rob MacKay January 30th
Jeff obviously dosn’t sleep… nice work – what a great tut!
( )MBzle January 30th
i haven’t done a login system for my new website, yet but i’m sure this will come in handy.
thanks1
( )VIkram January 30th
I’m still waiting for part 2 of the photo site tutorial
although this was pretty cool. always love the awesome work you guys do. thanks a lot.
( )Saurabh Shah January 30th
nice tutorial.. m gonna use it soon … thnx for sharing …
( )Jonathan Cousins January 30th
You are using Windows 7 right?
Do your program work OK on it?
( )Max January 30th
I agree with my previous speaker: very useful! I’ll be using it soon.
( )Designer January 30th
wow….. nice and simple tut
( )Tom Kenny January 30th
Excellent stuff. This is something that I know I will need in the future.
( )owain Llewellyn January 30th
Just what I need!!
Thanks Jeff!
( )Owain January 30th
Brilliant. A nice and detailed walk through of a sometimes tricky topic. Thank you. Can’t wait for part 2. : )
( )Kevin Martin January 30th
I’ve been wanting to expand my knowledge with prepared statements. I heard they were a lot faster, because database doesn’t have to interpret the same SQL over and over again.
Thanks!
( )james January 30th
a very useful tutorial. thanks Jeff!
( )EdpeppeRs January 30th
thx one more time, JW!
( )i don’t know how to do this and i’m really not into database stuffs.. but, i hope i learn one day. .^^
icomir January 30th
Much appreciated
( )AnDi January 30th
Thanks Jeff, u are the best….
( )Neil January 30th
If it is a very simple website, ten lines of code in your ASP.net web config and you are done. Right out of the box, it includes a timeout feature and a referrer redirect so when you log back in after being timed out, it takes you back to the page you were on when you were timed out.
.Net also has some super easy to use controls that allows for registration, roles and permissions, forgot password and login status.
This site seems to be mainly focused on PHP, which is a shame because .Net is extremely powerful and has some really easy to use, rich functionality right out of the box.
( )Stephen Coley January 30th
How do prepared statements protect from sql injection anymore than using mysql_real_escape_string()?
It’s called Mysql Improved, but it seems like you’re writing more to do the exact same thing you would with just plain old mysql.
Can you explain how this actually benefits the programmer? So far it just seems like a more complicated way of doing things.
( )Dan Harper January 30th
I’ve also had problems with CS4 with it indenting my code by a stupid amount, but it has seemed to have fixed itself.
Also, Dreamweaver plays up on its syntax highlighting when you open a PHP-only page which doesn’t have a close tag (very annoying when using CodeIgniter!).
( )Timothy January 30th
Nice. I don’t normally see login tutorials that include the use of prepared statements. Interesting.
( )Jason Karns January 30th
Part 2 ought to contain OpenID support.
( )Bill January 30th
Great job !
( )Bill January 30th
@Tip: If you use another programming language, ‘->’ in pHP is the ‘.’ in others like C# …
( )Bill January 30th
One thing i couldn’t figure out is why we are removing a cookie if we haven’t set any ?
( )Noam Smadja January 30th
Great cast!
though i think you could have dropped the “how to make a 2 input and submit button form”… would have shortened it by almost 15 mins…
( )Stephen Coley January 30th
@Bill
We have set a cookie, just not directly. The function session_start() creates a cookie and stores the session id in there. Even if we close the session, that doesn’t exactly delete the cookie. I believe that is why Jeff was doing it manually.
( )Dan January 30th
I love this website. Better than any book.
Question though (it might be answered – I haven’t watched the whole video):
Doesn’t PHP auto time out a session? Is setting a time out critically important? If so, I’ve got a few sites to fix.
( )Joshua Schoenaker January 30th
Thank you very much for this, can’t wait for part deux!
( )Andy January 30th
Jeff,
Great screencast, still watching. With your gripe about DreamWeaver not setting your indented tag correctly it actually is because your if statement was missing some closing parentheses and so Dreamweaver was not sure where your starting bracket was.
OK, now on with the rest of the show
( )Daniel Silva January 30th
I’m getting this error:
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /var/www/login3/classes/Mysql.php on line 6
Why?!?
( )ThE_OwNeR May 28th
Check if you dont miss a } someweren
( )capnjeremy January 30th
Don’t forget, the label “for” attribute should point to the -ID- of the form element, not the name. (This makes it so you can click on the label to focus the form input)
( )jon January 30th
Great stuff and I’m sure it would make a lot more sense if I understood PHP.
I’m also following Jeff’s Diving into PHP screencasts over at Themeforest, but can anyone suggest a good book(s) about beginning with PHP for someone with no programming experience? I know html and css but many books assume a background in one form of programming or another.
( )PHP Learner January 30th
thanks for the tutorial. it was great to see a real class being developed as i am starting to delve into OOP in PHP.
Also, the tag, gets added if you hold CTRL and press enter. You can change it in the shortcuts.
( )Bill January 30th
Cool tutorial
( )Jeffrey Way January 30th
@jon – “PHP Solutions” is the best one I’ve found so far.
( )Bryan January 30th
Your tutorials are awesome! They are exactly what I need! Thank you
( )Aliaspanther January 30th
Any chance some of these screencasts can be covered as a normal text/picture tutorial? My home connection is to slow to load these videos, and I try to avoid streaming videos at work as much as possible since our business is online based. Don’t want to be selfish and steal the bandwidth reserved for our clients.
Thanks! I’m currently enjoying the jQuery for Absolute Beginners series, at least those are nice and short so I can watch at home.
@jon – I read through PHP & MySQL For Dummies and found it to be worthwhile. The examples in it aren’t always tailored to what you may want to use the languages for, but they give you the jist of the possibilities. And it doesn’t assume you have any previous programming experience (hence the For Dummies).
Cheers!
( )Meshach January 30th
Thanks very much for this tutorial Jeff.
Really really helpful.
( )Jeffrey Way January 30th
@Aliaspanther – Normally, a text tutorial would be included with the screencast. But I covered so much in this series that it would taken a REALLY long time to create a written tutorial as well.
If you have ITUNES installed, do a search for NETTUTS. That way, you can download the video and view it anytime you like!
( )Sebastian January 30th
@Jeffrey – Wow, I love your screencasts! I have been learning so much from watching your work process. I really appreciate all the work you put into Nettuts. I visit every day anxious to learn more!
Thank you!
( )Taylor Satul January 30th
Cool, I really needed this
( )Robert January 30th
A tip to all of you saying that putting opening “{” at the same line as the statement or beneath it is the same thing, is totally wrong. If you ever get into “real” programming such as C, C++ or any other heavier language, you will learn the hardway that putting the opening tag will screw up your debugging. A good practise is ALWAYS put the opening beneath…
like:
So use it beneath!
( )function()
{
}
If it was jQuery for example… Also you will most likely get turned down at a professional interview
Robert January 30th
This is just a test envato – please remove the comment after!
Robert
January 30th
A tip to all of you saying that putting opening “{” at the same line as the statement or beneath it is the same thing, is totally wrong. If you ever get into “real” programming such as C, C++ or any other heavier language, you will learn the hardway tha
( )Jeffrey Way January 30th
@Noam – I agree somewhat. But that’s the great thing about the videos. If you’re advanced enough, you can simply fast forward a few minutes.
( )dude January 30th
dude…. windows? really?
( )ms January 30th
Unless I missed a modified idiom, don’t you mean “I bit off more than I could “chew”
( )Jeffrey Way January 30th
@ms – Hah. Whoops.
@dude – These comments always make me laugh. Yes Windows…really. I think that both Mac and Windows should be used.
I keep waiting for the day when I receive a knock on my door from people preaching about the “word of Mac”. It reminds me of being ten years old and arguing at the school lunch table about whether Nintendo or Sega was better.
Nevertheless, I do love…and use both.
–
P.S. For the record, I picked Nintendo.
( )Harnish January 30th
Cool tutorial
( )M.A.Yoosuf January 30th
@Neil you are correct but Open source rox, than paid solutions. still what u re talking about ABC solution, they simply in to marketing and getting money as much they want.
but Open source for every one!, you, me , Beginner, advance user bla bla, i don’t don’t think there is a shameless, that because of avoiding a paid technology
( )M.A.Yoosuf January 30th
@Jeffrey Way – thank you for listing for my comments, continue with OOP
so far as a beginner i have catchup approximately 70%, i guess once more i gotta watch it as you said
( )Frank Mawn January 30th
Hey Jeff, great tut!
Regarding your problem with Dreamweaver that doesn’t indent your line correctly – it’s simply because you had a mistake in your if statement. It’s some kind of warning that Dreamweaver gives ya!
( )trex279 January 30th
Anyway to download the tutorial without itunes?
( )M.A.Yoosuf January 30th
@trex279 why cant u use real player, it has a capturing feature, but slow :S
( )WebGyver January 30th
Awesome stuff!
Thank you for taking the time to get people started with web site log-in systems. As pointed out in some of the other comments, there’s always so much more you COULD do to protect your web site.
Cross-site scripting (XSS) is another weird but potentially harmful issue that I would love to see covered in any potential follow-up tutorials.
Again, keep up the good work.
( )Wassim January 30th
@Neil – Dear friend, please use whatever technology you like but don’t say “Shame”. A bad developer do nothing but preaching the pros of the technology he THINKS he likes, a good developer is always open minded just like any artist who tries to express his thinking via any form of expression. And this is it: Todays web uses oepn standards and 100% of my production (freelance scripting, graphic design) is done with 100% opensource software and my clients are just happy with the results; and I’m happy
@all: I just want to say to everybody here: There are no limitations in the Web industry, and if any; they are just in your imagination.
@Jeff: nice swing Jeff
( )ekkalak January 30th
Thank You Jeffrey
( )Vasili January 30th
I’m was wondering why you didn’t close the PHP tags at the end of the files (eg. constants.php). Also, require_once() is very slow. Might I suggest a config.php file?
( )Jeffrey Way January 30th
@Vasili – True – require_once() is slower; but is sometimes necessary.
In reference to the constants.php file, there’s no need for a closing php tag.
( )James January 30th
Lol! I think its epic when you kept saying “or die” lol i love the way you say it!
Also very very good tut, Thank you very much
( )Aaron January 30th
Nice tutorial. Mind not using the green border when zooming in next time? You can disable it in Camtasia’s preferences.
( )David Singer January 30th
Adding a salt and using SHA1 or better would make it much more secure. MD5 was broken years ago.
( )RealToughCookie January 30th
Cool tutorial! cant wait for part 2
@David Singer
Doesn’t Wordpress use MD5? If it does and MD5 has been cracked then im worried :0
( )Ali January 30th
YES Jeffrey, Nintendo was always better than Sega in my book…. ha ha
( )Jeffrey Way January 30th
@David – Yeah, I agree. We’ll be adding a salt in part 2.
( )Raman January 30th
Great tutorial.
( )Meshach January 30th
@Jeffery: Sega is better. Kidding, kidding, lol.
( )Abderrahmane Tahri Jouti April 29th
Noooo
Nintento is better
( )ked January 30th
MD5 has been broken, but most online Reverse MD5 hash lookup scripts simple crumble at the first sight of a non dictionary based password.
( )Dave January 30th
We actually bought an old SNES from ebay a couple years back and I failed my degree in construction solely because of mario kart and mortal combat.
Now I’m studying multimedia. Mario saved me so Nintendo is best!
( )D January 30th
Hello, How do I fix this error?
“Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /nfs/c03/h04/mnt/57407/domains/login.dcwatts.com/html/classes/Mysql.php on line 6″
( )christian January 30th
There must be something wrong with my server setup (MAMP). Both the site I created from the tutorial and the downloaded tutorial site files both show me the index.php page after I log out with these errors:
===============================
Notice: Undefined index: status in /Applications/MAMP/htdocs/login/membershipSite/classes/Membership.php on line 30
Warning: Cannot modify header information – headers already sent by (output started at /Applications/MAMP/htdocs/login/membershipSite/classes/Membership.php:30) in /Applications/MAMP/htdocs/login/membershipSite/classes/Membership.php on line 30
===============================
Everything works fine until I get to this point.
So I switched to my regular system server and everything worked just fine. Although not part of the tutorial
any ideas as to why a MAMP setup wouldn’t work and the system setup does?
( )David Singer January 30th
@RealToughCookie
Yes WordPress does, and they get a lot of shit for it it. I think the only reason they don’t change it is backwards compatibility.
This is how you should do it:
SELECT user_id, username, password_hash, salt FROM users WHERE username = :username LIMIT 1
if (hash(’sha256′, $password . $salt) == $password_hash) {
( )// ok
} else {
// not ok
}
Keith Walter January 30th
@Christian – I had the same problem and found a way to fix it. Go to
MAMP > conf > php5 > php.ini
Find output_buffering and change it to a number, such as 4096 like it suggests. This will fix your problem.
( )Keith Walter January 30th
@Christian – Also don’t forget to reset the server before you try again.
( )David Singer January 30th
Your also missing a call to: session_regenerate_id()
Without this in your code its very simple to steel someones session/login to their account. See http://en.wikipedia.org/wiki/Session_fixation
For part 2:
public function isSsl() { return isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == ‘on’; }
Will determine if your running SSL or not. Then you can force people to use SSL with this:
public function forceSsl() {
if (PRODUCTION) {
if (!$this->isSsl()) {
$url = ‘https://’ . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$this->redirect($url);
exit(0);
} else {
return true;
}
} else {
// only use SSL in production
return true;
}
}
Also while relative URL’s may work sometimes they are not allowed in HTTP/1.1. See: http://us.php.net/header
( )David Singer January 30th
More part 2 ideas:
Create an interface class for the database. Then do
class Mysql implements InterfaceDb {}
Then
class Db extends Mysql {}
That way in your Membership class you can make calls to Db rather than Mysql. Should anyone want to use your code with another database (say PostgreSQL) then all they would have to do is write
class Posgressql implements InterfaceDb {
// implement the methods
}
Then change:
class Db extends Posgressql {}
This would make your code much more portable.
Also much of the database class can/should be static as it can be beneficial to use one database connection across many other objects. If in the future you created other classes say User, Group, Account, etc they could all share a database connection.
( )Brandon January 31st
Great tut!
I keep getting this error:
Warning: main(Mysql.php): failed to open stream: No such file or directory in /home/content/b/e/m/bemarketing215/html/classes/Membership.php on line 3
Warning: main(Mysql.php): failed to open stream: No such file or directory in /home/content/b/e/m/bemarketing215/html/classes/Membership.php on line 3
Fatal error: main(): Failed opening required ‘Mysql.php’ (include_path=’.:/usr/local/lib/php’) in /home/content/b/e/m/bemarketing215/html/classes/Membership.php on line 3
Please help!
( )Symplicity00 January 31st
Awesome Tutorial!!!!
( )Though “one-hour” seemed a bit scary at first, it’s worth “a whole month”
Cant wait to see the next tutorial, like creating a form to add info to database or stuff or so.
christian January 31st
@Keith – Hey, thanks a lot! That did the trick. And how in the heck did you figure that one out?
( )Keith Walter January 31st
Multiple google searches and passing through articles and forum posting. I don’t remember exactly where it was.
( )RealToughCookie January 31st
@Jeffery Way
Can you confirm if this login system is suitable and secure enough for a business environment. I want to use a login system on our company’s site so share files with my colleges.
Is this right for me?
( )Aayush January 31st
The tag comes because you press shift+enter
Great tutorial though…continue with OOP
Thanks
( )Ferdy January 31st
Great tutorial. Suggestions for the next part:
- adding salt (as others mentioned)
- protecting the login from from a dictionary attack (by increasing the response time for it to load based on #attempts)
- checking the source of the post (so that no remote script is doing automated posts)
- UTF8 support/checks
I know these are kind of advanced topics, but none that can be skipped if people actually build their custom login forms and expose them on the webs.
( )greg606 January 31st
Jeff, you are great!
( )What a great tutorial! It beats those from lynda.com hands down!
What a great introduction to OOP!!!!!!
Please don’t stop you work!
Adam Coppard January 31st
I see that you use functions like so: function authenticate($un, $pwd){ } But I use them like so: function authenticate(){ $un = $_POST['un'] }
( )This always seems to work, dragging the $_POST value from the other page. Is one method better than another, or am I just being lazy?
Nei January 31st
@Wassim – I wasn’t preaching ASP.net, PHP is a great language, BUT so is .Net. And while PHP is covered in this blog quite frequently, ASP.net is not. I was simply voicing my opinion, and as a daily reader of this blog, I would love to see some more articles on ASP.net.
( )Chris January 31st
This works on my home server setup just not on my paid hosted setup at Siteground.
I can enter a correct username/password and it will still popup the incorrect username/password box.
Must be a setting in there PHP setup.
( )Jeffrey Way January 31st
@Nei – I agree with you. I personally love ASP.NET. Don’t worry – we have a bunch of .NET screencasts coming in February.
Stay tuned.
( )Saeed Jabbar January 31st
Thank you so much , this is exactly what I’m currently working on and will benefit of a great benefit.
@chris did you configure the mysql database and import all the data?
( )Zeke January 31st
I use MAMP (http://www.mamp.info/en/index.php) on OSX. Can anyone let me know how to turn on debugging for PHP? When there is an php error I just get a blank page.
( )Chris January 31st
@Saeed:
Yes, the database exists with the same values as the one on my home server. The only code I modified was the constants.php to match up to the new MySQL values on my hosted site.
( )Zeke January 31st
For the people getting this error: Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /var/www/login3/classes/Mysql.php on line 6
Make sure that you are running PHP5 and not PHP4 on you server.
( )brian January 31st
Zeke, You can view your errors in Applications/MAMP/logs/php_error.log
( )Saeed Jabbar February 1st
@Zeke use Xamp for OSX ,put the contents of your file in a folder in the htdocs.
@Chris that seems odd ,check for typos or whitespaces.
( )Mojo February 1st
Extremely useful tutorial, thanks! This will definitely come in handy for a few projects I have lined up.
( )Zac February 1st
I have to agree with Stephen Coley. Why fatten your code to protect against sql injection when php’s mysql_real_escape_string() is probably a better option, especially for small applications. Look at Example No. 1 on this page:
http://us3.php.net/manual/en/function.mysql-real-escape-string.php
That’s a beautiful example of an injection-safe query.
( )connor February 1st
@christian @Keith Walter
somehow enabling output buffering on php.ini didn’t work for me so I added ob_start(); and ob_end_flush(); , works great now, any idea why?
looks like this now
function confirm_Member() {
session_start();
ob_start(); if($_SESSION['status'] !=’authorized’) header(”location: login.php”);ob_end_flush();
}
btw, thanks @David Singer for the the ssl protection, i feel safe…er
( )Ben February 1st
I am using the same present usage of mysqli in an small application I’m building, but the use of bind_params method returns an error :
Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn’t match number of parameters in prepared statement [...]
I think I declared it the right way though :
$statement->bind_param(’iss’, $id, $name, $filename);
$statement->execute();
while ($data = $statement->fetch())
{
return $data;
}
Indeed, the id is properly declared as an integer, then two variables $name and $filename declared as strings… There shouldn’t be an error right? I’m running the script on a local WAMP machine which runs the latest version of php, with the php_mysqli module activated…
This is driving me crazy! I might come back to good ol mysql_connect()…
Did anyone encountered the same problem?
Chears everyone, and thanks a lot Jeffrey for the awesome screencast!
( )Kim Andersen February 1st
Uhh i’m looking forward to the .NET screencasts Jeffrey
I have always wanted to lear .NET, so this will be great.
About this screencast: Super work, thouhg I am not that great at OOP. Could you make a screencast about OOP in PHP, for beginners
, as well in the future?
( )Nei February 1st
@Jeffrey Way, looking forward to them – thanks for the heads up
( )Neil February 1st
ahh i missed the “L” from my name haha
( )Chris February 1st
@Saeed: I’m guessing the only place I could be making a mistake is the constants.php file since that’s the only file I’m editing. Although, I must be making the connection to the database because I’m not getting the DIE message.
Is there anyway to see what’s being passed using Firebug? I know in jQuery its console.log, is there a similar command for PHP?
( )Saeed Jabbar February 1st
@Chris you can install FirePHP for firebug and give that a try.
( )Jeffrey Way February 1st
@Ben – It’s because the number of parameters doesn’t match your query.
Can you paste in your query? Is it different from the one I used?
( )João Pedro Pereira February 1st
I’ve liked it
. But it has some code that could be better implemented.
( )David February 1st
@Zeke: Had the same problem a few days ago. You can fix it by going to your MAMP Folder and open the php.ini file in the folder “conf/php5″ or “conf/php4″ depeding on what version you are using. Then search for “display_errors = Off” and turn it “On”. After this you need to restart the server.
Fantastic Tutorial, Jeff! I just got started with PHP two weeks ago and your screencasts got me started very quick. Thank you so much.
( )Zeke March 20th
Thanks!
( )Chris February 1st
@Saeed:
Its looking like it gets to the membership.php spot but its not actually querying the database or connecting at all..sort of like its bypassing it completely. So its only spitting out the response since $ensure_credentials is never being set. Wonder if there’s an extension that’s not loaded or something. Its PHP5.2.5 so I’d imagine it should work.
I can total omit the constants.php and not even fill in any database stuff or I can hard code everything and it doesn’t work either way. I’ve tried using a form method of GET so I can see the values being passed in the query string and everything is being sent through the form just fine.
( )Arik Lewis February 1st
Nice Tutorial. Maybe on the next one you can talk about ACL.
( )Mathew February 1st
Hi Guys,
Getting a problem with this one if anyone can help out.
My Ensure Credentials is not coming back true,
Changes I have made include mysql.php
$query = “SELECT *
FROM permissions
WHERE username = $un AND passwd = $pwd
LIMIT 1″;
And Setting my database connection in the constants.php file.
Code is obviously getting stuck at this line in in mysql.php
if($stmt = $this->conn->prepare($query)) {
( )Mathew February 1st
Looks like miy problem is exactly same as Chris’s 2 posts up as same version og PHP etc.
( )Jeffrey Way February 1st
Matthew – You’re using prepared statements, yet you aren’t using “?” for your query.
“…WHERE username = ? AND passwd=?
Then bind the parameters to pass $un, and $pwd.
( )Mathew February 1st
Hi Jeff,
Thanks mate figured that out not long after.
Thanks so much for the quick reply and looking forward to your next article
( )spidro February 1st
very nice tutorial thanks jeff
( )shedh February 2nd
when will part 2 be out?
will their be a registration script to go with this?
Some one please answer
( )Martin February 2nd
seriously looking forward to part 2!
many thanks
( )Chris February 3rd
It must be a CS4 problem because I have never had the problem with CS3 and before….
I use Coda or Text Mate now for PHP style coding. I would use windows if they had these programs for windows computers.
( )Chris February 3rd
Jeff,
Thanks for this tutorial. WOOF! I learned from this.
( )Chris. February 3rd
Cheers for this great tutorial,
I want to make a development, I would like to display the users first name on the members page (i.e. Welcome Chris). I have created two new columns in the database (FirstName, Surname). I understand that i will need to implement a new function in Mysql.php, but how do I create the query. Do I need to add more data to the session (i.e. ID)? If so how do I get the database to return that to the session when a User logs in.
I know this is a little Detailed, but this tutorial has given me a hunger to get coding and create something special!
I’m Looking forward to part 2!
( )Andres F February 4th
Outstanding job as always Jeffrey. I will be studying this over and over again. Thanks for the great work you are doing for the community and for taking the time to share you knowledge. Tis very much appreciated! This site is terrific!
( )iDevelopThings February 6th
What I was looking for.. Thanks!
( )tom February 7th
Very nice tutorial.
But, this is not working the same with me. So please send orginal code if you can.
Thanks.
( )NAVI February 7th
TANKS
( )hijz February 7th
it’s really good to know it!
thanks
( )Rui Raposo February 7th
Hello to all,
First off Jeffery, really nice tutorial, really what i was looking for.
Im trying to implement the system on my project, but im getting this error after i put my pass and user on the form…
Fatal error: Class ‘mysqli’ not found in /home/rotary/public_html/2008-09/2009-2010/d1960/classes/Mysql.php on line 9
Anyone can give me some lights? i created the DB and all the fields and stated on the tutorial.
Some help would be nice,
Tks in advance,a nd keep up the good work Jeffrey.
( )Alessandro February 9th
Hi JW,
i tried to upload the script on my webspace. Locally it works fine, but online i get always the “incorrect username/password” message.
I think the function mysql->fetch() returns always NULL and i don’t know why. Do you have any solution?
Thank you very much.
@Rui: Do you have the MySqli extension enabled?
( )Alessandro February 9th
A typo. The function i was referring to is $stmt->fetch()
( )unclebob123 February 11th
great tutorial, but im getting the error message
Warning: mysqli::mysqli() [mysqli.mysqli]: (28000/1045): Access denied for user ‘username’@'localhost’ (using password: YES) in C:\wamp\www\membershipSite\classes\Mysql.php on line 9
Warning: mysqli::prepare() [mysqli.prepare]: Couldn’t fetch mysqli in C:\wamp\www\membershipSite\classes\Mysql.php on line 20
Does anyone know how to fix this?
( )Chris February 12th
@Alessandro,
I’m still having that same problem as well. I posted a while ago about that..I dont see any differences between my setup and my web hosts.
I’d like to know if there is something that may need to be enabled on the web host.
( )Yiannis February 15th
i can’t open every flash on this site.i dont know what should i do
( )bill February 15th
Hello, iv(ve got the same problem as unclebob…
Any idea ?
Thanks
( )Brandon February 18th
Hey can someone please help me!
I keep getting this fatal error:Call to a member function on a non-object in line 20
This is the code. I did change line 6 to “var”
conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die(’There was a problem connecting to the database.’);
}
function verify_Username_and_Pass($un, $pwd) {
$query = “SELECT *
FROM users
WHERE username = ? AND password = ?
LIMIT 1″;
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param(’ss’, $un, $pwd);
$stmt->execute();
if($stmt->fetch()) {
$stmt->close();
return true;
}
}
}
( )Can someone please help me out!!!!
Sergio February 22nd
brandon
I keep getting that same problem. its weird though it was working the first time i tried it, and it the script works perfectly when i use it on my server, but when i go on another server(godaddy) it gives me this error. I two had to change private to var for it to work in godaddy
( )Magicfap February 22nd
when your adding the userrname and password as constants, you use a predefined username of Jeffery_Way and a password of nettuts, since im new to this I don’t know where they are set. You tutorials are great, and im hoping to use this, but since i am having problems with the login password that you set it will not work yet.
( )Amy February 23rd
Thanks, i havnt completed it but its helping ALOT :]
( )John Smith February 23rd
Very useful, works perfectly. HTML I’ve pretty much masterd, but PHP always had scared me, this was a great introduction to it and I have learnt a lot about it, thank you.
( )David February 24th
@Jeff Still desperately waiting for part 2 of this screencast. Tried to get my head around sessions myself but being a php-newbie this ended not the way I wanted it to. Can you tell when part 2 will be online? Anyway, keep up your great work. I always enjoy your tutorials. Thank you.
( )Roeland February 25th
Great tutorial. Also curious when the next part will be put up! Thanks for all your work!
( )D March 2nd
Great.
( )Angel March 2nd
Just what I need!
Thanks Jeff!
( )peter March 6th
can you suggest how to setup this script and serve different pages to people once they are logged in?
is there an automated way to setup the program to redirect directly to the user’s page? right since i am using a login system for a small group of people, i manually edit the code each time i need to add a new user and do an if statement against the usernames to serve specific pages. although if someone is logged in and guesses another person’s username, they could jump to someone else’s page.
help!
( )HtmlGifted March 8th
was wondering if you could show more on how to implement this into a existing site.. looking to password protect for e commerce and was not all that familiar with php. scripting. and this video was very help full. also do you have any recommendations for how to find a good online free data base for php. user name and password storage.
( )LaLo March 10th
Jeff,
( )Very nice…implementation went smoothly…When will part 2 come out?
Bill March 11th
Awesome tutorial, I am really anxious to see part 2!
( )Angel March 11th
Part 2 Pleaseeeeeeeeeeeeeeeee!
( )Chuck March 13th
Yea, where is part 2? It’s about that time.
( )aureus March 14th
kkkkkkkkooooooooool!!
( )Ara March 15th
Nice tut, having a little problem. I copied everything line by line and my function verify_username_and_pass always returns false. It never even tries to execute my sql statment. Any suggestions?
( )Rick Bross rbross3@att.net March 15th
This is simply amazing, im going to dive deeper into PHP now, thanks to you!!
( )James March 16th
This tutorial really rocks. Can’t wait for part 2 include the CSS tutorial too.
( )BinaryKitten March 17th
the For attribute of the tag doesn’t refer to the name attribute of an input element, but rather the ID attribute..
eg UserName:
more info: http://www.w3schools.com/tags/tag_label.asp
( )Sarah March 17th
Hello all,
( )pleasure to write to you ,Can i develop that login without using database but by simply using text file and if yes how could it be done?
Thank you for time and consideration
mushroom March 17th
Very useful tutorial. THX
Cheers
( )Hamza Oza March 18th
is there going to be part 2 to this
( )Steve March 18th
just another user waiting for part 2
any release date penned?
( )Ryan March 19th
WTB Part 2. Paying +2 Karma.
( )Joshua Newton March 24th
hey do you know when you will bring out part two?:)
really wanna know how to do a lot of extra things
do you think you will be able to show people how to make a forum ? like adding comments that add onto our domain space database? that would be a really cool tut!
( )Joshua Newton March 24th
by the way sorry, how do you add your database made in phpmyadmin, to your domain? along with the Other files ?
its really confused me :Si know how to add them i just dont know how to with the phpmyadmin database LOL!
someone please help
would be appreciated!
( )Omar March 25th
how can I get more information or updates to this post/code?
( )wal April 1st
Nice tut. I’m waiting for Part2 too.
( )Brodie001 April 1st
This was a great Tutorial. It was also a nice and simple intro to class based OOP programming. I’m longing for part 2.
( )adam April 7th
Well,why i enter a valid username and password,but it seems that i can’t log in.why?
( )i had followed the way,but still cannot successfully make a perfet login system,who can help me?
you can refer to http://www.elathy.com/membershipsite to focus on my problem,thanks.
adam April 7th
sorry,it’s http://www.leathy.com/membershipsite
( )allan April 14th
This tutorial is a bomb. But I wonder where mysqli and the $this->conn->prepare() is from. Anyway this one really is great
( )Tedd April 17th
which capture software are you using to capture this its looks professional
( )good tutorial
Arthiis April 20th
Hey, I am having some problems… dunno why, I followed your video and tried your actual files, all to no avail… I have SQL 5.0.67-community and It comes up with the error:
Fatal error: Class ‘mysqli’ not found in /classes/Mysql.php on line 9
Please help!
( )tarek April 20th
hi guys could someone give me a little help to make it works:
( )when i click on login button it doesn’t take me anywhere but when i try to enter a random username and password it return the error message .
here is my files i haven’t a nother solution so i uploaded them to rapidshare.
http://rapidshare.com/files/223755870/membership.rar.html
thank’s jeffrey
thank’s guys
Buco May 1st
A little off-topc, but I am really curious how you got that sidebar on the left of your screen? Did you use some software to install that sidebar? If yes, which?
Thanks,
Buco
( )omonisha May 5th
awsome
( )anus May 6th
wher’s part2?
( )kris May 8th
it’s not working for me in MAMP.
It let’s me see the secret launch code lol
I think for some reason it’s not destroying the session or not redirecting…
Anyone else with the same problem???
( )Brecht May 16th
I’m having the same problem when i integrate the script in my site but when i navigate to the source files i works perfectly :s
( )kris May 8th
found out why i had this:
if(isset($_SESSION['status']) && $_SESSION['status'] != ‘authorized’){
header(”location: login.php”);
}
should have had this
if(isset($_SESSION['status']) != ‘authorized’){
header(”location: login.php”);
}
I tried to be cool and check if the session was set but I screwed it up. why would the first notation work though?
( )rocky May 9th
Hey Guys ,
getting error called “call to member function on a non object” on
( )this line
if($stmt = $this->conn->prepare($query)) in php
i know this is a problem with version .
how to use in php4 and this help must be greatly appreciated .
José Maria Barros May 10th
I have the exact same problem.
But my version of PHP is 5…
Call to a member function verify_Username_and_Pass() on a non-object in Membership.php on line 9
Can anyone help me ???
( )José Maria Barros May 10th
forgot: the line 9 has this code:
$ensure_credentials = $mysql->verify_Username_and_Pass($un, md5($pwd));
mikail May 14th
hii guys, i am trying to source code but my firewall says
HAVP – Access Denied
Accesss to the page has been denied
because the following virus was detected
( )Clamd: PUA.Script.Packed-1
reittenok May 15th
223
( )Schenelle May 16th
Nice Tut
For PostgreSQL I replaced the verify_username_and_pass method to the following. Hope it would benefit some of you.
public function verify_username_and_pass ($un, $pwd) {
$query_str = “select * from users where username=$1 and pwd=$2″;
if ($statement = pg_prepare($this->dbconn, $query_str)){
( )$result = pg_execute($this->dbconn, array($un, $pwd));
}
if(pg_fetch_array($result)) {
return true;
}
}
arnold C May 20th
why its not working with me..I still got the error message that I have wrong username and password,but I see in phpmyadmin it was correct,can someone help me
( )jincignee May 25th
Отлично написано. Позитива конечно не хватает, но читал на одном дыхании
( )Thomas May 26th
Hey great tutorial. I’m a bit of a noob and i keep getting the error…
Fatal error: Class ‘Msql’ not found in …/membershipSite/classes/Membership.php on line 8
$mysql = New Msql();
Could someone help me?
( )seo May 31st
Warning: mysqli::mysqli() [mysqli.mysqli]: (28000/1045): Access denied for user ‘username’@'localhost’ (using password: YES) in C:\AppServ\www\giris\classes\Mysql.php on line 9
Warning: mysqli::prepare() [mysqli.prepare]: Couldn’t fetch mysqli in C:\AppServ\www\giris\classes\Mysql.php on line 20
sql ? share…
( )Ari June 18th
im having the same exact issue, did you find a solution?
( )netput November 7th
same problem
Hauke June 9th
really great
( )Istvan June 10th
Thanks … it was easy to learn … and put in practice
I’m checking new nettuts from you …
( )Jason A. June 17th
Love the this tutorial. Still waiting for part 2, though. Still going to happen??
( )Moneyxl June 18th
Is it possible to download the screencast itself?
( )Del June 23rd
Hi,
I’m gettin an error saying:
“Fatal error: Call to a member function prepare() on a non-object in C:\wamp\www\membershipSite\classes\Mysql.php on line 20″
This happens whether I use the correct username/password or not. I went to line 20:
if ($stmt = $this->conn->prepare($query)) {
but don’t see what is wrong. Any ideas?
( )Adrian June 29th
if the user ignores location headers, they will not have to log in to see the secret launch codes.
( )saad July 4th
Thanks for every thing.
( )mark July 6th
i’m looking forward to your future tutorial
thnx jeff. you rock!
( )gway July 25th
nice tut!
( )i was wondering what is the method to hash a password ?
John August 9th
Die() function is not working. It’s not dying.
I simply don’t have database installed even though i when i try with existing database and WRONG password. It’s not dying.
It just shows error at the top of the page. I just want to make it die().
( )D'Arcy August 20th
Do Prepared Statements return differently with UPDATE instead of SELECT.
( )I’ve been using this tutorial to understand Prepared Statements and I have them working fine, except my UPDATE queries return to the previous class false, even if they work just fine.
Hope that makes sense.
puur August 24th
Hii… this video stops in minute 26.. i whats up there ???
( )SAT August 25th
Excellent !! Very precise and we all forgive you for your mistakes during the video ^^
I love your tutorial !
( )Thanks again
Bre September 1st
Awesome tut – Just what I was looking for.
Trying to upload the working files to my server that has php myadmin built in.
I’m pretty sure Ive changed the “constants” file correctly with my user name, password etc but when I login to the login.php page it keeps saying that I have an invalid username/ password although it is one I have entered into php myadmin.
Any ideas?
(un: ‘test’ | ps: ‘12345′
( )Awofe September 4th
Hi Jeff!
Where can I get part 2 of this tutorial?
( )Lucas September 6th
What should I use instead of this:
conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die(’There was a problem connecting to the database.’);
}
function verify_Username_and_Pass($un, $pwd) {
$query = “SELECT *
FROM users
WHERE username = ? AND password = ?
LIMIT 1″;
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param(’ss’, $un, $pwd);
$stmt->execute();
if($stmt->fetch()) {
$stmt->close();
return true;
}
}
}
}
If I dont have MYSQLI module installed?
( )Sebastian September 8th
Hey when will part to be posted? BTW great tuts only reason i got a plus account is to watch the content you post
thanks
( )Shane September 15th
Hey Thanks! I enjoyed that, and learned a bunch. I’ll be going through your other stuff for sure.
( )Michael October 2nd
Part 2 would be great.
( )Aaron Bentley October 6th
Hey everybody, how can i get the details for the user currently logged in?
As i am building an application form, which inserts to mysql db.
Any ideas?
( )Patel October 12th
Great tutorial! Thanks a lot to make it very easy and understandable. I believe 2nd part of tutorial is in demand! cant wait…..
( )Aaron Bentley October 13th
@Jeff – Is part 2 on the way soon?
( )stefn October 15th
Thank you for this tutorial, I got it working pretty close to my needs.
However, how would I go about redirecting the visitor to the page he was *trying* to reach before getting stopped by the login.php page, after he has sucsessfully logged in?
( )stefn October 16th
I actually got this working the way I wanted (with a little help from some nice people at irc://dalnet/php)
Modified Membership file:
( )http://pastebin.com/fdd81909
Milo October 26th
I still have a problem, both in my own and the downloaded tutorial version of Mysql.php.
I get this error:
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /nfs/c05/h04/mnt/77028/domains/silktonguegamblers.com/html/classes/Mysql.php on line 6
As I don’t know any php, I have no idea how to solve it. Does anyone know why this error comes up? My server is uding PHP5.
( )Milo October 26th
Nevermind. It was a regular problem with (mt) servers that it automatically reverts back to PHP4. I had to create a line in the .htaccess file to instruct it to stick to PHP5.
( )