user2875099
user2875099

Reputation: 11

Executing query through HTML form

views/registration.php

<form action="classes/registration.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit">
</form>

classes/registration.php

if(isset($_POST['submit']))
{
 // Define form variables
 $username = $_POST['username'];
 $password= $_POST['password'];

 // Insert form data into database
 $query = "INSERT INTO users (username, password)
 VALUES ('$username', '$password')";
 if(mysqli_query($conn, $query))
 {
    echo "Registration successfull.";
 }
}

The problem is, when I click submit, I get a blank page. The query isn't being executed.

I thought the problem might be because my values aren't setup correctly, so I did the following:

VALUES ('$_POST['password']', '$_POST['password']')";

but that gives me an error, presumably because I am using ' inside of '

So now I am back to square one, unsure of why my query isn't being executed

Upvotes: 0

Views: 3030

Answers (2)

Ataboy Josef
Ataboy Josef

Reputation: 2101

Your file naming and paths seem to be mismatching(as per the file names you provided).

No matter if you keep:

views/registration.php
views/classes/registration.php

But if you follow:

--/classes
         /registration.php

--/views
        /registration.php

[Note: '--/' is the path of your root directory]

Then the form action classes/registration.php won't go anywhere. So change it:

<form action="../classes/registration.php" method="post">

I suggest to follow the naming convention:

filename- for pages with HTML forms, and

filename_action- for action pages

Also notice the possible error cases mentioned by user baao in the other answer.

Upvotes: 1

baao
baao

Reputation: 73211

You are getting a blank page because you don't echo something if $_POST submit isn't set.

if(isset($_POST['submit']))

is never true as your $_POST['submit'] is never set. You need to give your submit a name, this (the name) is what get's POSTed / what you can access within $_POST[' /*name of input*/ ']

Change your form to the following, then you should see your

echo "Registration successfull.";

HTML:

<form action="classes/registration.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit"> <!-- <<<<<<<<<<< here -->

As a sidenote, you should absolutely consider using a prepared statement. Running a registration form with your insert query is like an invitation for people keen on ruining your server. You might want to try the query like this:

$query = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$query->bind_param('ss',$username,$password);
$query->execute;

This way, you will be secured against mysql injection.

Upvotes: 3

Related Questions