简体   繁体   中英

Trying to connect a database in php, but get syntax error

I am trying to make a login page using a database I created in PHPMyAdmin, but everytime I run it, I get a syntax error on line 2 of login.php, and I do not know why it will not work. I am sure I entered the code correctly. When I run it, I get an error:

Parse error: syntax error, unexpected ':' in login.php on line 2

login.php

<?php
    $dsn = 'mysql:host=localhost;dbname=dbase';
    $username = 'user1';
    $password = 'pass';

    $error = "";

    try{
        $db = new PDO ($dsn, $username, $password);
    }

    catch (PDOException $e){
        $error = $e->getMessage();
    }
// end of database connect

    $user = $_POST['user'];
    $pass = $_POST['pass'];

    $query = 'SELECT * FROM users WHERE user = :user AND pass = :pass';

    $statement = $db->prepare($query);
    $statement->bindValue(':user', $user);
    $statement->bindValue(':pass', $pass);
    $statement->execute();
    $valid = ($statement->rowCount() == 1);
    $result = $statement->fetch();
    $statement->closeCursor();

    if ($valid){
        $greeting = $result['email'];
        $permit = ", login success";
    }

    else{
        $greeting = $user;
        $permit = ", invalid credentials";
    }

?>
<!DOCTYPE html>

<html>
    <head>
        <title>Scheduler</title>
    </head>

    <body>
        <h1><?php echo $greeting.$permit; ?></h1>
    </body>
</html>

loginpage.php

<html>
    <head>
        <title>Scheduler</title>
    </head>

    <body>
        <form action = 'login.php' method = "post">
            <h1>EZ-Scheduler</h1>

            <h2>Please login to view rosters</h2>

            <table>
                <tr>
                    <td>Username:</td>
                    <td><input name = "user" type = "text" size = "25"></td>    
                </tr>
                <tr>
                </tr>   
                <tr>
                    <td>Password:</td>
                    <td><input name = "pass" type = "password" size = "25"></td>
                </tr>
            </table>    
                <p><input type = "submit" name = "button" value = "Login"></p>
            </table>
        </form>
    </body>
</html>

try this stuff and see

<?php
    $username = 'user1';
    $password = 'pass';

    $error = "";

    try{
        $db = new PDO ('mysql:host=localhost;dbname=dbase', $username, $password);
    }

    catch (PDOException $e){
        $error = $e->getMessage();
    }
// end of database connect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM