Jump to content

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!

Edited by Pain
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

Edited by requinix
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.