How do I authenticate a user in PHP / MySQL?

前端 未结 7 1516
春和景丽
春和景丽 2020-12-08 09:26

So recently I learned how to properly add a username and password to a database. My database is usersys, and the table storing user information is called userdb. The table h

7条回答
  •  庸人自扰
    2020-12-08 09:32

    One way to do it (DISCLAIMER: not necessarily best-practice):

    $result = mysql_query("SELECT id FROM userdb WHERE username='$esclcusername' AND  password='$escpassword'") or die(mysql_error());
    $row = mysql_fetch_array( $result );
    $id = (int)$row['id'];
    if($id > 0) {
        //log in the user
        session_start();
        $_SESSION['userId'] = $id;
        $_SESSION['username'] = $displayname;
    }
    

    ... and on pages that require authentication:

    session_start();
    if(!isset($_SESSION['userId'])) {
        die('You need to be logged in!!!');
    } else {
        echo 'Welcome ' . $_SESSION['username'];
    }
    

    Read more about PHP sessions.

提交回复
热议问题