3

嗨,我很新,PHP我已经研究过phpmysql点点。

我已经创建了一个mysql database和一个table但我不知道创建一个php登录script..

谁能帮帮我

我试图用下面的代码连接数据库,但它不工作我在我的本地电脑上运行我的脚本

<?php



    $dbHost = "mysql";
    $dbUser = "root";
    $dbPass = "1234567";
    $dbDatabase = "db_name";
    $db = mysql_connect($dbHost,$dbUser,$dbPass)or die("Error connecting to database."); 
 ?>

连接到数据库时出错

4

2 回答 2

4

尝试将您的主机名更改为localhost

此外,您应该真正考虑使用PHP 数据对象(通常称为 PDO)以获得更安全的登录。

于 2012-08-06T08:48:09.237 回答
1

你这个错误连接到数据库错误,因为你已经提到mysql如果database host你在本地php中运行你的主机是localhost

php登录脚本如下

将以下代码保存在Php文件中并将其命名为login_page.php

<form action="verify.php" method="post">
    User Name:<br>
    <input type="text" name="username"><br><br>
    Password:<br>
    <input type="password" name="password"><br><br>
    <input type="submit" name="submit" value="Login">
</form>

将以下代码保存在Php文件中并将其命名为verify.php

<?php
if(isset($_POST['submit'])){
    $dbHost = "localhost";        //Location Of Database usually its localhost
    $dbUser = "xxxx";            //Database User Name
    $dbPass = "xxxxxx";            //Database Password
    $dbDatabase = "db_name";    //Database Name

    $db = mysql_connect($dbHost,$dbUser,$dbPass)or die("Error connecting to database.");
    //Connect to the databasse
    mysql_select_db($dbDatabase, $db)or die("Couldn't select the database.");
    //Selects the database

    /*
    The Above code can be in a different file, then you can place include'filename.php'; instead.
    */

    //Lets search the databse for the user name and password
    //Choose some sort of password encryption, I choose sha256
    //Password function (Not In all versions of MySQL).
    $usr = mysql_real_escape_string($_POST['username']);
    $pas = hash('sha256', mysql_real_escape_string($_POST['password']));
    $sql = mysql_query("SELECT * FROM users_table 
        WHERE username='$usr' AND
        password='$pas'
        LIMIT 1");
    if(mysql_num_rows($sql) == 1){
        $row = mysql_fetch_array($sql);
        session_start();
        $_SESSION['username'] = $row['username'];
        $_SESSION['fname'] = $row['first_name'];
        $_SESSION['lname'] = $row['last_name'];
        $_SESSION['logged'] = TRUE;
        header("Location: users_page.php"); // Modify to go to the page you would like
        exit;
    }else{
        header("Location: login_page.php");
        exit;
    }
}else{    //If the form button wasn't submitted go to the index page, or login page
    header("Location: index.php");    
    exit;
}
?> 

要检查用户的天气,请logedin使用以下代码

<?php
session_start();
if(!$_SESSION['logged']){
    header("Location: login_page.php");
    exit;
}
echo 'Welcome, '.$_SESSION['username'];
?> 
于 2012-08-06T08:47:49.690 回答