PHP Session从数据库中获取数据

时间:2014-01-23 11:13:38

标签: php mysql database session

我有以下代码:

   <?php
    session_start();
    ?>

<!DOCTYPE html>
<html>
<body>
<form name="form1" method="POST">
    <table>
        <tr>
            <td>Username</td>
            <td> <input type="text" name="text1"></td>

        </tr>
        <tr>
            <td>Password</td>
            <td><input type="password" name="pwd"></td>


        </tr>
        <tr>
            <td><input type="submit" name="submit1"></td>           

        </tr>
    </table>
</form>


</body>
</html>



<?php
include 'config.php';
mysql_select_db("sess_db",$con);

?>

<?php
if(isset($_POST['submit1'])) {
      $result=mysql_query("SELECT username,password FROM siteinfo ");
      $result2=mysql_fetch_row($result);
      $count=mysql_num_rows($result);
    $nm = $_POST['text1'];
    $pwd = $_POST['pwd'];
    if ($result == $nm && $result == $pwd) {
        $_SESSION['luser'] = $name;
        $_SESSION['start'] = time();
        //the expire u put it
        $_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
        header('Location: homepage.php');
    }
    else {
        echo "Please Enter a Correct Username & Password ! ";
    }
}
?>

在登录页面我必须输入用户名:joseph和密码:moon

但我想删除这两个变量$name&amp; $password并将其链接到包含用户名和密码的数据库,如果我输入其中一个将我重定向到

  

homepage.php

2 个答案:

答案 0 :(得分:1)

试试这个。但这太简单了

     <?php
            if(isset($_POST['submit1'])) {

                $name = "Joseph";
                $password = "moon";
                $nm = $_POST['text1'];
                $con=myssql_connect('localhost','root','');// mysql_connect('your host name','database username','database password')
                mysql_select_db('your database name',$con) or die("Can't select DB");
                $pwd = $_POST['pwd'];
                $qry="SELECT * FROM login_labe WHERE username='$name' AND 
password='$password'";
                $result=mysql_query($qry);
                $res=mysql_fetch_array($result);
                 $nm=$res['username'];
                 $pwd=$res['password'];
                if ($name == $nm && $password == $pwd) {
                    session_start();  ///////////////You need to add session_start()
                    $_SESSION['luser'] = $res['your name form DB'];
                    $_SESSION['start'] = time();
                    //the expire u put it
                    $_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
                    header('Location: homepage.php');
                }
                else {
                    echo "Please Enter a Correct Username & Password ! ";
                }
            }
            ?>

答案 1 :(得分:0)

首先,您应该在$_POST['text1']$_POST['pwd']上添加一些过滤器,以避免SQL查询中的注入或意外行为。

$name = $_POST['text1'];
$pw = $_POST['pwd'];

然后,只需构建一个这样的查询:

SELECT count(*) from user_table where name = $name and pwd = $pw

如果count != 0,则关联名称/密码正确,您可以将用户重定向到主页。

这是非常基础的,你可以做得更安全。