PHP - Session variables with prepared statements and parameterized queries - php

I tried to write a registration form. On submition it suppose to:
Get the data from the inputs to the sql database - as a row in the table.
Add the users email address as a session variable.
Redirects them to a second page.
It all happens, but it adds two identical rows instead of one.
I'll appreciate any answer you can give me that will explain why my script adds the same row twice into the database.
PHP:
<?php
ob_start();
session_start();
if($_POST) {
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$error = "";
$link = mysqli_connect("xx", "xx", "xx", "xx");
if (mysqli_connect_error()) {
die("the connection was failed");
}
if ($email || $password || $name) {
$stmt = $link->prepare("INSERT INTO `Family` (email, password, name) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $email, $password, $name);
$stmt->execute();
if($stmt->execute()) {
$_SESSION['email'] = $email;
header("Location: session.php");
$stmt->close();
} else {
echo "it failed";
}
}
}
HTML:
<html>
<head>
</head>
<body>
<h1>Registration Form</h1>
<form method="post">
<p>Email:</p>
<input type="email" name="email">
<p>Password:</p>
<input type="password" name="password">
<p>Name:</p>
<input type="text" name="name">
<br><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

Related

Attempting to Submit HTML Form to Database Has Blank Output

I am new to PHP and web development, and trying to create an HTML form that will submit data into MYSQL.
Upon checking phpmyadmin after submission of the form, it shows that there has been a row submitted,
however the row is completely blank. I had a problem before this one, that instead of a blank row, it would be "1" submitting instead of the data inserted into the HTML form. Now, no data submits into the database.
Here is the PHP:
<?php
Include("connection.php");
// HTML Identification
$lname = isset($_POST['lastname']);
$fname = isset($_POST['firstname']);
$email = isset($_POST['email']);
$phone = isset($_POST['phonenum']);
$addr = isset($_POST['address']);
$city = isset($_POST['city']);
$state = isset($_POST['state']);
$zip = isset($_POST['zipcode']);
//Database Insertion
$sql= "INSERT INTO CustomerInfo (LastName, FirstName, Email, PhoneNum, Address, City, State, ZipCode)
VALUES ('$lname', '$fname', '$email', '$phone', '$addr', '$city', '$state', '$zip')";
// Insertion
$ds= mysqli_query($conn, $sql);
// - Insertion Confirmation
if($ds)
{
print 'Row Inserted!';
print ' Response Recorded!';
}
?>
The HTML Form:
!DOCTYPE html>
<html>
<head>
<title> GS Entry Form </title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css#2/out/water.css" </link>
<style>
h1 {text-align: center;}
h2 {text-align: center;}
</style>
</head>
<body>
<h1>Customer Entry Form</h1>
<h2>Please Input Contact Information</h2>
<form action="database.php" method="POST">
First Name:<br />
<input type="text" name="firstname" />
<br /><br />
Last Name:<br />
<input type="text" name="lastname" />
<br /><br />
Email:<br />
<input type="text" name="email" />
<br /><br />
Phone Number:<br />
<input type="text" name="phonenum"/>
<br /><br />
Address:<br />
<input type="text" name="address"/>
<br /><br />
City:<br />
<input type="text" name="city"/>
<br /><br />
State:<br />
<input type="text" name="state"/>
<br /><br />
Zip Code:<br />
<input type="text" name="zipcode"/>
<br /><br />
<button type="button" name= "submit" value= "submit" />
</form>
</body>
</html>
Here, also, is the connection.php referenced:
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create Connection
$conn= mysqli_connect("$servername:3306","$username","$password","$dbname");
// Check Connection
if ($conn->connect_error)
{
die("Connection failed: " .$conn->connect_error);
}
else echo "Connection successful! "
?>
I don't think it has anything to do with the connection, but I figured I would post it to cover all the bases. The attached imgur picture is what my database has been looking like after submissions have been made.
I truly am not sure what to do now, any help would be greatly appreciated.
Thank you! -G
EDIT:
This is what my PHP code looks like after the changes suggested from #EinLinuus:
<?php
Include("connection.php");
// HTML Identification POST
if(isset($_POST['firstname'])) {
$fname = $_POST['firstname'];
}else{
die("Firstname is missing");
}
if(isset($_POST['lastname'])) {
$lname = $_POST['lastname'];
}else{
die("Lastname is missing");
}
if(isset($_POST['email'])) {
$email = $_POST['email'];
}else{
die("Email is missing");
}
if(isset($_POST['phone'])) {
$phone = $_POST['phone'];
}else{
die("Phone Number is missing");
}
if(isset($_POST['addr'])) {
$addr = $_POST['addr'];
}else{
die("Address is missing");
}
if(isset($_POST['city'])) {
$city = $_POST['city'];
}else{
die("City is missing");
}
if(isset($_POST['state'])) {
$state = $_POST['state'];
}else{
die("State is missing");
}
if(isset($_POST['zip'])) {
$zip = $_POST['zip'];
}else{
die("Zip Code is missing");
}
//Database Insertion
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt= $conn->prepare("INSERT INTO CustomerInfo(FirstName, LastName, Email, PhoneNum, Address, City, State, ZipCode) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssssss', $fname, $lname, $email, $phone, $addr, $city, $state, $zip);
$stmt->execute();
// Insertion
$sql= mysqli_query($conn, $stmt);
// - Insertion Confirmation
if($ds)
{
print 'Row Inserted!';
print ' Response Recorded!';
}
$stmt->close();
$conn->close();
?>
My HTML remains the same, besides adding ID attributes to each variable to no effect. I appreciate the help!
The isset function returns if the variable is declared or not -> the return type is a boolean.
$test = [
"hello" => "world"
];
var_dump(isset($test["hello"])); // bool(true)
var_dump(isset($test["something"])); // bool(false)
You can use isset to check if the field exists in the $_POST variable, but don't save the result of the isset function to the database. If you do so, the boolean will be converted to a number (true => 1, false => 0) and this number gets stored in the database.
Example:
if(isset($_POST['lastname'])) {
die("lastnameis missing");
}
$lname = $_POST['lastname'];
Security
This code is vulnerable to SQL Injections. You should never trust user input. I'd recommend to use prepared statements here:
$stmt = $mysqli->prepare("INSERT INTO CustomerInfo (LastName, FirstName, ...) VALUES (?, ?, ...)");
$stmt->execute([$lname, $fname]);
In the SQL statement, replace the actual values with ?. Now you can execute the statement and pass the values to the execute function. In the example above, $lname will replace the first ?, $fname the second, ...

how to do signup validation in php

The problem is; I'm trying to fix the sign-up validation but still, it still saved in our database even if it's empty hopefully someone can provide explicit information as to were wrong in coding.
even if one of input box is empty it is still saved to our database table
<!DOCTYPE html>
<html>`enter code here`
<head>
<title>Sample Registration Form</title>
</head>
<body>
<form action="submit.php" method="POST">
<input type="text" name="userid" placeholder="USER ID"><br>
<input type="text" name="firstname" placeholder="FIRST NAME"><br>
<input type="text" name="lastname" placeholder="LAST NAME"><br>
<input type="text" name="email" placeholder="EMAIL"><br>
<input type="password" name="password" placeholder="PASSWORD"><br>
<button tabindex="submit" name="submit">Sign up</button>
</form>
<a href='login.php'><button type='submit' name='submit'>Proceed to Login</button></a>
</body>
</html>
the code above is the sign-up page
<!DOCTYPE html>
<html>
<head>
<title>Submit </title>
</head>
<body>
<?php
$dbservername = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "blogfinal";
$connect = mysqli_connect($dbservername, $dbusername, $dbpassword, $dbname);
if(isset($_POST['submit'])) {
$userid = $_POST['userid'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$checker = array("userid", "firstname", "lastname", "email", "password");
$Error = true;
foreach ($checker as $values) {
if(empty($_POST[$values])) {
echo "Error";
$Error = true;
} else {
$sql = "INSERT INTO userinformation
(userid, firstname, lastname, email, password)
VALUES ('$userid', '$firstname', '$lastname',
'$email', '$password');";
}
if(mysqli_query($connect, $sql)) {
echo "Saved Successfully<br>";
echo "<a href='login.php'><button type='submit' name='submit'>Proceed to Login</button></a>";
} else {
echo "Error Description: " . mysqli_error($connect);
}
}
}
?>
</body>
</html>
the code above is the submit function.
the problem is when we hit the sign-up even if the input-box is empty and it is still functioning and saved to our database, instead of a password, email, user, or first name is required.
[if you leave it empty then proceed to submit it show saved even there's no data on it.][1]
[the image after we hit the submit button.][2]
[hence, if we at least insert 1 data required and proceed to submit it still saved to our database, instead of showing that the other data is required][3]
[1]: https://i.stack.imgur.com/gVc0i.png
[2]: https://i.stack.imgur.com/Aizjl.png
[3]: https://i.stack.imgur.com/A04c0.png
The problem is that you're checking if each value is empty withif(empty($_POST[$values])) within a foreach loop. This if has an else that is running every time.
So even if one of the fields in empty, the query will always execute if there's at least 1 field that is not empty.
You should change the logic to make that even if just one field is empty, then the query doesn't run.
Here's a quick fix:
$Error = false;
// Check if all fields are not empty
foreach ($checker as $values) {
if(empty($_POST[$values])) {
echo "Error";
$Error = true; // If even just one field is empty, the $Error variable will be true
break;
}
}
if(!$Error) { // Check if I got an error
$sql = 'INSERT INTO userinformation,(userid, firstname, lastname, email, password) VALUES ("?", "?", "?", "?", "?");';
$stmt = $connect->prepare($sql)
$stmt->bind_param('sssss', $userid, $firstname, $lastname, $email, $password);
if($stmt->execute())
// The rest of your query
}
Furthermore please refer to the comment by #RiggsFolly to your question as your code has security issues connected to SQL Injection.

My database is not adding users when I signup

This is my HTML file:
<div class="form">
<form action="register.php" method="POST" class="register-form">
<input type="text" placeholder="Username" name="username" required/>
<input type="password" placeholder="Password" name="password" required/>
<input type="text" placeholder="Email" name="email" required/>
<button type="submit">Create</button>
<p class="message"> Already Registered? Login
</p>
</form>
<form action="login.php" method="POST" class="login-form">
<input type="text" placeholder="Username" name="username" required/>
<input type="password" placeholder="Password" name="password" required/>
<button type="submit">login</button>
<p class="message">Not Registered? Register</p>
</form>
This is my PHP file:
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if (!empty($username) || !empty($password) || !empty($email)) {
$serverName = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "account";
//create connection
$conn = new MySQLI($serverName,$dbUsername,$dbPassword,$dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$SELECT = "SELECT email From users Where email = ? Limit 1";
$INSERT = "INSERT Into users (username, password, email) values(?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$stmt->store_result();
$stmt->fetch();
$rnum = $stmt->num_rows;
if ($rnum==0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("sss", $username, $password, $email);
$stmt->execute();
echo "New record inserted sucessfully";
} else {
echo "Someone already register using this email";
}
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
I have a database called account, with a table called users, columns called id, email, username & password. The ID is an INT, and selected as primary. And the rest is set as VARCHAR.
When I enter some names in the form, and press signup, it's giving me the result "New record inserted successfully", so I have no idea, why this doesn't work.
Your problem is the way you use mysqli. As I have said in the comments mysqli is not suitable for beginners, the API is very cumbersome.
Look at the lines before your INSERT statement. You perform a SELECT statement, presumably to check if the email has been used before and then you bind the result variable. The variable is called $email. You overwrite your user input with the result from SELECT. But this is not the right way.
The simple solution would be to name the variable something else, but the right answer is that you should fetch a count from the SQL not the value. See adjusted code below:
<?php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
$email = filter_input(INPUT_POST, 'email');
if ($username && $password && $email) {
$serverName = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "account";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new MySQLI($serverName, $dbUsername, $dbPassword, $dbname);
$conn->set_charset('utf8mb4'); // always set the charset
//Prepare statement
$stmt = $conn->prepare("SELECT COUNT(email) From users Where email = ? Limit 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($exists); // we fetch the count
$stmt->fetch();
if (!$exists) {
$stmt = $conn->prepare("INSERT Into users (username, password, email) values(?, ?, ?)");
// Don't forget to hash the password and never store the real password anywhere
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt->bind_param("sss", $username, $hash, $email);
$stmt->execute();
echo "New record inserted sucessfully";
} else {
echo "Someone already register using this email";
}
} else {
echo "All field are required";
}
I remove the unnecessary code and removed the store_result() and num_rows. They are not helpful in this situation. Instead fetch a count of matching rows and check if the count is not 0 with if(!$exists)

trying to send form values to database

i have a problem in sending my form values to mysql database i readed all other topics and i did what they wrote but i didn't get what i want please help me :(
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "13838383";
$dbname = "users";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
?>
<?php
include("../includes/functions.php");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../public/stylesheets/style.css" type="text/css">
<title>Our WebPage</title>
</head>
<body>
<center>
<form action="input.php" method="post">
<fieldset>
<legend>Register</legend>
<span>UserName: </span><br />
<input type="text" name="username" placeholder="USERNAME"><br /><br />
<span>PassWord: </span><br />
<input type="text" name="lastname" placeholder="PASSWORD"><br /><br />
<input type="button" name="submit" value="submit"><br /><br />
<fieldset>
</form>
</center>
<?php
?>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$addUserQuery = "INSERT INTO users (username, password) VALUES ({$username}, {$password});";
$added = mysqli_query($connection, $addUserQuery);
if ($added) {
echo '<br>Input data is successful';
} else {
echo '<br>Input data is not valid';
}
}
?>
</body>
</html>
and my problem is i don't know know what should i enter in action attribute in form tag thanks please help
Simply put, your variables aren't quoted, so your query is being turned into this (If someone submitted 1337user as the username, and P#ssw0rd as the password):
INSERT INTO users (username, password) VALUES (1337user, P#ssw0rd);
When it should be:
INSERT INTO users (username, password) VALUES ('1337user', 'P#ssw0rd');
Bind your variables instead: How can I prevent SQL injection in PHP?
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$addUserQuery = mysqli_prepare($connection, "INSERT INTO users (username, password) VALUES (?, ?)");
mysqli_stmt_bind_param($addUserQuery, "ss", $username, $password);
$added = mysqli_stmt_execute($addUserQuery);
if ($added) {
echo '<br>Input data is successful';
} else {
echo '<br>Input data is not valid';
}
}

PHP/MySQL Creates Blank Record In Database

I have a user input form(HTML) that is supposed to take the information and insert it into a MySQL database via PHP. The PHP apparently executes and echoes "Your registration has completed successfully". A record is created in the database but the columns are blank(I have removed my server, database, and password from the PHP code).
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title>User Portal</title>
</head>
<div class="inputContainer">
<header>
User Information Portal
</header>
<form action="php/userPost.php" method="post">
<label for=firstName">First Name</label>
<input type="text" id=firstName" name="fname">
<br><br>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lname">
<br><br>
<label for="eMail">Email</label>
<input type="text" id="eMail" name="email">
<br><br>
<label class="labelRole" for="userRole">Role -</label><br>
<input type="radio" id="userRole" name="role" value="Instructor"> Instructor
<input class="submitButton" type="submit" name="submit" value="Register">
</form>
</div>
</body>
PHP:
<?php
$sname = "server-name";
$uname = "username";
$pword = "password";
$dbname = "web_tech_test";
$conn = new mysqli($sname, $uname, $pword, $dbname);
if ($conn->connect_error) {
die("Connection failure: " . $conn->connect_error);
}
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
$sql = "INSERT INTO users (first_name, last_name, email, role)
VALUES ('$fname', '$lname', '$email', '$role')";
if ($conn->query($sql) === TRUE) {
echo "Your registration has completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This creates a new record in the DB but all the columns are blank. Any ideas why this may be happening?
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
this code returns a boolean, not a string value...
Use !empty() just for validation
example
if(empty($_POST['eMail'])) {
die("Email cannot be empty");
}
You're confusing the id and the name tags on the inputs.
The name tags are the ones which will be submitted as keys to your server.
Try this in your server php script after submitting your form to see which key/values are actually received by the server:
var_dump($_POST);
Also, if you want to check that all fields have been filled out, use something similar as this:
if (empty($_POST['firstName'])) {
die("firstname is empty!");
}
In your current example you're actually saving a boolean to your variables.
And, last but not least, never insert variables from a potentially unsafe source (like a user input) directly into your SQL. Use pdo: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers for this
Full code example to get you started:
//prepare your values
if (empty($_POST['fname']) || empty($_POST['lname']|| empty($_POST['email']|| !isset($_POST['role'])) {
die ("some values were empty or not set");
}
//prepare your database
$db = new PDO('mysql:host=server-name;dbname=web_tech_test;charset=utf8mb4', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //throw an exception if there is an error
//create your query
$stmt = $db->prepare("INSERT INTO users (first_name, last_name, email, role) VALUES (:first_name,:last_name,:email,:role)"); //create a query statement
$stmt->bindValue(":first_name", $firstName); //put your values into your statement
$stmt->bindValue(":last_name", $lastName);
$stmt->bindValue(":email", $email);
$stmt->bindValue(":role", $role);
if ($stmt->execute()) { //execute the query
echo "Your registration has completed successfully";
} else {
echo "Error :(";
}

Categories