Learning PHP, need some help

Soldato
Joined
15 Dec 2004
Posts
3,819
Hi,

I've been learning PHP over the weekend and have covered quite a bit with a very good tutorial I've been following :) I basically need to create a members area for a site. Now I know I could do it with cookies but obviously that isn't very secure so I wanted to do it with mySQL (the tutorial covered it as well) but am a bit confused on how to do it. So far, I have created a MyISAM table with the fields of 'user' and 'pword' and have the following script:

Code:
<?php

// Set Database Connection Parameters:

$host = "localhost";
$user = "********";
$pword = "********";
$dbase = "membersarea";

// Connect to Database:

$connect = mysql_connect($host, $user, $pword) or die('Could not connecto to database!');

// Select Database:

mysql_select_db($dbase) or die('Could not select database');

// Set User Input Variables:

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

// Define Query:

$query = "SELECT * FROM user_info";

// Execute Query:

$result = mysql_query($query) or die("Error in query: $query" .mysql_error());
$row = mysql_fetch_row($result);

// If Username and Password are correct, include the members page:

if (($row[1] == $username) && ($row[2] == $password)) {
	echo "Username and password accepted";
	echo "<br /><br />";
	include('membersarea.php');
}

// If the Username is correct but the password wrong, display the wrong username page:

elseif (($row[1] == $username) && ($row[2] != $password)) {
	echo "Username found but the password is incorrect";
}

else {
	echo "Username not found";
}


// Free Result Set Memory:
mysql_free_result($result);

// Close Connection:
mysql_close($connect);

?>

Now, the script works perfectly but I'm not sure what I have to do when I add more users. I understand that this is probably not the best way of doing things but I only started on saturday night :o So could anyone suggest a fix or a better way of doing things?

Thanks

Ben
 
Do a query like this (untested):

Code:
$query = 'SELECT * FROM user_info ' .
'WHERE user = "' . mysql_real_escape_string($username) . '" ' .
'AND pword = "' . mysql_real_escape_string($password) . '" ' .
'LIMIT 1';

If you don't get 0 results returned then you know that you've found a password/username match in the table.

Also, don't use * unless you need to.
 
Pine said:
Do a query like this (untested):

Code:
$query = 'SELECT * FROM user_info ' .
'WHERE user = "' . mysql_real_escape_string($username) . '" ' .
'AND pword = "' . mysql_real_escape_string($password) . '" ' .
'LIMIT 1';

If you don't get 0 results returned then you know that you've found a password/username match in the table.

Also, don't use * unless you need to.

Hmmm, any chance you could explain this a bit more? I've not seen that before :o Sorry for being a n00b :o :D

Thanks

Ben
 
As an aside, you should learn to comment your code properly. Avoid comments that just describe the code, like:

Code:
// Define Query:

$query = "SELECT * FROM user_info";

(Who doesn't know that $query = defines $query?)

You should just comment elements of the code whose purpose isn't immediately clear (although most of it should be), and even then just describe what the code is doing not exactly how it does it (unless it's fantastically complex).
 
Read my first post again: I AM LEARNING! :o

I accept that my coding isn't great but the tutorial I was using commented it like that so I just followed on. And as for the SQL syntax, there was only a couple of paragraphs on it and it only showed the syntaxes which I have used- nothing else and I didn't feel it was the right time to start another tutorial.

Anything else I've done wrong that is going to cause the whole world to come to an abrupt end?
 
robmiller said:
Calm down, I was only making a suggestion.

I know and I appreciate the suggestion so thank you but it just seemed like you were picking at the smallest of things. Now, for my original problem, can't I just add more lines like:

Code:
if (($row[1] == $username) && ($row[2] == $password))

but change 1 and 2 to 3 and 4 and so on respectivley? I'm trying to keep it simple :o

Thanks

Ben
 
mysql_fetch_row returns a numerically indexed array. It'd be best to use mysql_fetch_array/mysql_fetch_assoc, which both return associative arrays - that is, arrays where the key is the name of the field, and the value is that field's value.

So, you could use:

Code:
$result = mysql_query('
SELECT foo, bar
FROM table
WHERE foo = "4" AND bar = "lol"
');

while($row = mysql_fetch_array($result)) {
    echo $row['foo'];
    echo $row['bar'];
}

It's infinitely easier to use.

That said, you'd probably be much better off using a database abstraction layer, such as ez_sql, which would allow you to do:

Code:
$row = $db->fetch_row('
SELECT foo, bar
FROM table
WHERE foo = "4" AND bar = "lol"
');

echo $row->foo;
echo $row->bar;

Making everything a lot easier.

Sorry if this is a bit overwhelming to take in at once but you'll get there eventually :)
 
Trigger said:
Now, for my original problem
You don't need to do the user/password comparison in PHP - MySQL can do it.

Think about it - you store username and password details in the database, and the user has submitted a username and password to login with.

So, you can constructe a query to select all rows from the table where the username and password match the user-submitted details. If MySQL returns exactly one row then that means there's a match, which means you can carry on and log the user in. If there's no rows returned then there's no match, and you can show an error message :)

So, use this SQL statement:

Code:
$query = 'SELECT * FROM user_info ' .
'WHERE user = "' . mysql_real_escape_string($username) . '" ' .
'AND pword = "' . mysql_real_escape_string($password) . '" ' .
'LIMIT 1';

Then run mysql_query() with it like you've done with the old one, then use mysql_num_rows() (to which you pass $result, just like with mysql_fetch_row($result)) to work out how many rows MySQL returned. :)

Edit: Of course, you lose the functionality of seeing if there's a username match only this way (or, at least, you'd have to do two queries), but I prefer to give a generic "login failed" message than separate messages for a wrong username/password. That be just my preference, though.
 
Last edited:
Trigger said:
Now, for my original problem

Think through what you're doing.

You've got a username and a password that the user submitted. You've got the actual username and password in the database. You need an easy way to see if the password field in the database for the given user matches the one the user has submitted.

So, this is where the WHERE keyword comes in. SELECT tells mySQL to get some rows from the database; WHERE tells mySQL how to restrict the rows that are returned.

So, you need to do:

Code:
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);

$result = mysql_query("
SELECT username
FROM users
WHERE username = '$username' AND password = '$password'
");

If the username and password match, mySQL will return a result containing the username; if they don't, mySQL will return nothing. So, to check that, we use the mysql_num_rows function to check how many rows were returned in the result:

Code:
$numRows = mysql_num_rows($result);

if($numRows > 0) {
    // Username and password are okay
} else {
    // Username or password mismatch
}
 
Thank you to both of you, that makes much more sense now :) I'll read it through a few more times and then try it. Sorry for getting annoyed before- I thought I was being shouted at :o

Cheers

Ben
 
An observation: I don't understand why people try learning stuff from tutorials, they're generally pretty poor and don't cover things particularly well, if you're going to bother to learn how to do something you may as well learn how to do it properly. Get a book, they far surpass what's generally available off the web. Also, you need not actually pay for a book, just go to your local library. I can't speak for anyone elses library but the public one in Cambridge is pretty good, there's quite a variety of books available on this topic and you also get to borrow them for a full 3 weeks! :)

Sorry for shouting! :(
 
Pine said:
An observation: I don't understand why people try learning stuff from tutorials, they're generally pretty poor and don't cover things particularly well, if you're going to bother to learn how to do something you may as well learn how to do it properly. Get a book, they far surpass what's generally available off the web. Also, you need not actually pay for a book, just go to your local library. I can't speak for anyone elses library but the public one in Cambridge is pretty good, there's quite a variety of books available on this topic and you also get to borrow them for a full 3 weeks! :)

Sorry for shouting! :(

I don't really like tutorials or books - especially for something as (relatively) simple as PHP. You can grasp the basics of PHP just from RTFMing.
 
Instead of starting a new thread, I thought i'd ask here... I've just started on a little project to try and build up my skills by writing a helpdesk type program for school as we don't have one. Now, I have written the form which inputs the data to the database and that works fine. I also have the admin interface which reads all the values in the database and display them in a table.

I have created a row to show whether the job is done or not but don't know how to change the value without doing it manually. I have created a form button to do it on click but I don't know what code I need :(

I have a table called 'help_desk' with a field 'done' which will have the value 'yes' or 'no' and would like to know how to change it's value with a form button if possible please :)

Thanks :cool:

Ben
 
If I understand you correctly you're having trouble with changing values in a row that already exists in the database?

You need to be looking at using the SQL UPDATE statement.
 
Back
Top Bottom