php – I don't know why I can't connect to my database-ThrowExceptions

Exception or error:

I started learning PHP and MySQL. I have seen some instructions and tried to follow, but I just can’t get my head around the issue. Here are my codes.

<?php include('connect.php');?>
<html>
<head>
<title>PHP Project</title>
<link rel="stylesheet" href="style.css">
</head>

<body>
    <form method="post" action="connect.php">

    <h1>LOGIN</h1>
    <?php include('errors.php');?>

    <label for="uname">Username</label><br>
    <input type="text" id="username" placeholder="username" name="username"><br>

    <label for="email">Email</label><br>
    <input type="text" id="email" placeholder="example@mailextension.com" name="email"><br>

    <label for="password">Password</label><br>
    <input type="password" id="pswd" name="password"><br>

    <input type="button" id="btn" value="Login" name="Login">

    </form>
</body>
</html>

My supposed PHP connection to database and commands…

<?php

    $username = "";
    $email = "";..
    $password = "";
    $errors = array();

    // Connect to database
    $db = mysqli_connect("localhost", "root", "", "registration");

    // If the Login button is clicked

    if(isset($_POST["Login"])){
        $username = mysql_real_escape_string($_POST["username"]);
        $email = mysql_real_escape_string($_POST["email"]);
        $password = mysql_real_escape_string($_POST["password"]);

        // Ensure that all fields are filled properly
        if (empty($username)){
            array_push($errors, "Username must be filled");
        }
        if (empty($email)){
            array_push($errors, "Email must be filled");
        }
        if (empty($password)){
            array_push($errors, "Password is required");
        }

        if (count($errors) == 0){
            $password = md5($password);
            $sql = "INSERT INTO users (Username, Email, password) VALUES ('$username', '$email', '$password')";
            mysqli_query($db, $sql);
        }
    }

?>

My errors function…

    <?php if (count($errors) > 0): ?>

    <div class="errors">
            <?php foreach ($errors as $error): ?>
                <p><?php echo $error; ?></p>
                <?php endforeach ?>
    </div>
<?php endif ?>

So please can someone help me go through these and ell me what’s wrong, nothing happens when I click the login button, I don’t see any user details in my database…

How to solve:

Change <input type="button" id="btn" value="Login" name="Login"> to <input type="submit" id="btn" value="Login" name="Login">.

Also turn on error reporting in your PHP script.

Finally, look into prepared statements. They are crucial to any web developer and help to prevent SQL injection attacks. They are surprisingly easy to use and make your code more readable.

Leave a Reply

Your email address will not be published. Required fields are marked *