Building a blog bit by bit

Hi there

I really want to code a blog myself and have decided the best way for me to do this as Im a newcomer is to take it slowly and do it bit by bit.

The first part I want to build is the login part. Im guessing this is a different script for register…

Ive been reading and watching loads of tutorials but am finding it quite hard. May I post some code and you can tell me what you think…?


$username = $_POST["username"];
$password = $_POST["password"];

$connect = mysql_connect("localhost", "root", "") 

 || die ("Couldn't log you in!");

$query = mysql_query("SELECT * FROM users WHERE username = '$username.'");

$numrows = mysql_num_rows('$query');

if ($numrows !=0)
	while ($row = mysql_fetch_assoc ($query))	
		$dbusername = $row ["username"];
		$dbpassword = $row  ["password"];

//check to see if they match!

if ($username = $dbusername && $password = $dbpassword);
	echo "You're in!";
	$_SESSION["username"] = $username;
echo "Incorrect login!";
	die ("That user doesn't exist");

mysql_select_db("php_login") or die ("Couldn't connect to database");
	die("Please check and enter your username and password");

I have followed this from a tutorial and could I believe write somethng based off this myself but Im a bit worried about the ‘$connect’ variable. As you can see it specifies “my” admin details. If I was to use this code and attach it to a form a new user/follower was filling in, is this wise…does it need to be there…?

Any suggestions would be great as I wanna get each script I write as good as it can be before I move onto the next one.

PS thanks to everyone that has helped me so far.

First off, your connect should take place in another file, usually a config.php or conn.php file, so that it’s accessible to the entire site, and you just include it into your scripts with require_once(‘/path/to/conn.php’);

You’re not cleaning your inputs, which leaves your script wide open to an attack. At the very least you should use mysql_real_escape_string() in your SQL query. Also, don’t use SELECT *, as it’s lazy and you don’t need to retrieve that much information. You’re only checking the username and password, so only ask for those.

You’re checking if username and password are set, not if they’re empty. In most cases they will be set as POST variables, even if the user didn’t fill them in. So you should check to see if they contain a value: if($_POST[‘username’] != ‘’ && $_POST[‘password’] != ‘’), although, I’d check them individually so you can print more descriptive error messages to the user.

Your query on line 11 has an error. You put a period (.) after username.

Check for a match in the query, not in the script. It’s faster and uses less code.

‘password’ is a reserved word in SQL. Use passwd or something else.

The final SQL query should be something like “SELECT username,passwd FROM users WHERE username='”.mysql_real_escape_string($username).“’ AND passwd='”.mysql_real_escape_string($passwd).“’ LIMIT 1”

Here’s a very basic login script, which I believe does exactly what you wanted but with fewer lines of code. I whipped this up in a few minutes this morning (before coffee!), so I’m sure I overlooked something, forgot something or just plain included some bugs. However, it should give you an idea on how to simplify your code to do exactly the same thing. You should read up on include files, conn files, config files, etc as they will save you a ton of time and headaches. :slight_smile:


// setup an array for error messages
$errors = array();

// check if the submit button was clicked
if(isset($_POST['submit'])) {

	// check if a username exists
	if($_POST['username'] != '') {
		$username = trim($_POST['username']);
	} else {
		$errors[] = 'Please enter a username';
	// check if a password exists
	if($_POST['passwd'] != '') {
		$passwd = trim($_POST['passwd']);
	} else {
		$errors[] = 'Please enter a password';
	// no errors, check if user exists in the database
	if(empty($errors)) {
		$sql = "
		FROM users 
		LIMIT 1";
		$result = mysql_query($sql);
		$row = mysql_fetch_assoc($result);
		if(mysql_num_rows($result) > 0) {
			// login successful
			$_SESSION['username'] = $row['username'];
			// redirect to admin page
		} else {
			// login unsuccessful
			$errors[] = 'Please check your username and password';
	} else {
		$errors[] = 'There was an error...';
	// print error messages
	if(!empty($errors)) {
		foreach($errors as error){
			echo $error.'<br />';
<!-- put form here -->

why LIMIT 1 ???

surely you don’t allow the same username/password combination to exist more than once!!

heck, even the same username alone more than once in the users table is a disaster

Before coffee, Rudy! Geeze. :wink:

You’ve raised an excellent point about table design and UNIQUE indexes. I didn’t touch on encrypting a password and performing a lookup on that either. That’s something else for Ethan to check into.

Thanks tgavin this is some great stuff.

When you say check in the query could you tell me where I would write that…? Also may I ask what is “trim”?

Like I say Im doing it step by step and this is a great start. Im gonna have a look at the encrypting passwords stuff next I think. I believe its something to do with sha1 and md5…?

One more thing would generating an error with incorrect details take the user to another page…? I’m trying to make it so the error is displayed under the text box. Do many people do this…?

Thanks again man

What I mean by check for a match in the query is to use the query to find out if the username and password match a record in the users table - which mine did. You were checking for a match using PHP, which you can most certainly do, however using SQL is faster and uses less code, as you can see from my example. :slight_smile:

Encrypting is simple. Keep in mind that you need to encrypt the password before inserting it in your users table, and then search for the encrypted password. Also, your passwd field should be VARCHAR(40), as sha1, by default, creates a 40 character string.

In the registration script, create the password like so.

$passwd = $_POST['passwd'];
$passwd = sha1($passwd);
$sql = "INSERT INTO users (username,passwd) VALUES ('".mysql_real_escape_string($username)."','".mysql_real_escape_string($passwd)."')";

Then, in the login script you would do the same thing

$passwd = $_POST['passwd'];
$passwd = sha1($passwd);
$sql = "SELECT username,passwd FROM users WHERE username='".mysql_real_escape_string($username)."' AND passwd='".mysql_real_escape_string($passwd)."'";

Keep in mind that these are simplified and you’ll still need to properly clean your POSTed data.

trim() just trims the white space from the beginning and end of a string. PHP: trim - Manual

Generating errors the way I showed echos the errors right there on the page. I have mine in a function called messages() that prints error messages (red text), success messages (green text) and plain old system messages.

Tgavin you are a legend

Thankyou so much. Ive been watching and reading tutorial after tutorial and only now are things starting to make sense. Your explanation of things seem so much clearer

I noticed you wrote the first script before morning coffee, that would have taken me about a week lol

Im in Asia and its about 2 in the morning here now so Id better try and catch some zeez. I’m guessing Ill be dreaming about post and gets tonight .

Once again thanks so much.