Jump to content

Starting A Session In A Class


Pain

Recommended Posts

Hi there.

 

I am trying to retrieve stuff from the database and then assign it to a session variable like this:

 

function selectDB() {
global $mysqli;
if ($stmt = $mysqli->prepare("SELECT username, password FROM ww3_users WHERE username = ? AND password = ?")) {
$stmt->bind_param('ss', $new_username, $new_password);
$new_username = $_POST['username'];
$new_password = $_POST['password'];
$stmt->execute();
$stmt->bind_result($username, $password);
while($stmt->fetch()) {
return $username;
}
$_SESSION['username'] = $username;
return $_SESSION['username'];
}
else
{
return false;
}
}

 

Is it the correct way to assign like this?

$_SESSION['username'] = $username;
return $_SESSION['username'];

 

The code successfully retrieves username and pwd from the db, but the session variable is empty..

 

thanks!

Link to comment
https://forums.phpfreaks.com/topic/270805-starting-a-session-in-a-class/
Share on other sites

There's other problems with that function, but to answer the question yes, that's what you would do.

 

1. The function is called "selectDB" but does much more than that

2. $mysqli should be either a class-level variable (if you're using a class) or a function parameter, not pulled from global scope

3a. Your if block branches on whether the statement could be prepared. That should never, ever fail

3b. The decision between returning the username or false should depend on what the query found. You're branching too early

4. The username and password should be function parameters, not pulled from $_POST

5. Assuming that there's only one combination of username/password, a while loop doesn't belong - there's only ever one row

6. You're using plaintext passwords. Stop that

7. Your while loop returns the username immediately. The session stuff will never get executed

8. The function sets something (tries to) in the session. I doubt that's the right place to do it

9. Since the purpose of the function is to validate a username/password login, make it return true (if valid) or false (if invalid) and let the calling code do what it wants with that result

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.