Attempting to Submit HTML Form to Database Has Blank Output - php

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, ...

Related

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.

PHP - Session variables with prepared statements and parameterized queries

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>

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 :(";
}

Why does my Register form still not input data into my MySQL tables

I'm trying to link a register page with my login page to allow new users to register an account to use on my application. I've linked the form up to my tbl_Users table on MySQL in which holds all the information that the users would input into this form. I've properly set everything up using queries and such and the form displays properly at the very least. However when I click submit, the page just refreshed with the fields now empty again and no new data within my table on the database. Where am I going wrong? (Extra-note: I'm still in the process of coding in the safety code to prevent sql-injections)
ConnectorCode.php
<?php
$conn = mysqli_connect("localhost", "b4014107", "Win1", "b4014107_db2") or die (mysqli_connect_error());
?>
Register.php
<?
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include('ConnectorCode.php');
if(isset($_POST['submit'])) {
$FName = $_POST['First_Name'];
$LName = $_POST['Last_Name'];
$Email = $_POST['Email'];
$UName = $_POST['User_Name'];
$Password = $_POST['Password'];
$FName = mysqli_real_escape_string($conn, $FName);
$LName = mysqli_real_escape_string($conn, $LName);
$Email = mysqli_real_escape_string($conn, $Email);
$UName = mysqli_real_escape_string($conn, $UName);
$Password = mysqli_real_escape_string($conn, $Password);
$sql = "SELECT Email FROM tbl_Users WHERE Email='$Email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
echo "Sorry, the email you are trying to enter already exists";
}
else
{
$query = mysqli_query($conn, "INSERT INTO tbl_Users(First_Name, Last_Name, Email, User_Name, Password) VALUES ('$FName', '$LName', '$Email', '$UName', '$Password')");
if($query)
{
echo "Thank you for registering";
}
header('Location: Index.php');
}
}
?>
<!DOCTYPE HTML>
<head>
<title>Register</title>
</head>
<body>
<h1> Register Page </h1>
<p> Please fill in the form to register <p>
<form method="post" action="">
<fieldset>
First Name: <br />
<input name="First_Name" type="text" class="input" size="25" required /> <br /> <br />
Last Name: <br />
<input name="Last_Name" type="text" class="input" size="25" required /> <br /> <br />
Email: <br />
<input name="Email" type="email" class="input" size="25" required /> <br /> <br />
Username: <br />
<input name="User_Name" type="text" class="input" size"25" required /> <br /> <br />
Password: <br />
<input name="Password" type="password" class="input" size="25" required /> <br /> <br/>
<input type="submit" name="submit" value="Register!" />
</fieldset>
</form>
</body>
</html>
You do not meet the condition isset($_POST['VALUES']) because you don't have field with name="VALUES".
Change
if(isset($_POST['VALUES'])) {
to
if(isset($_POST['submit'])) {
You had a lot missing...
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once 'ConnectorCode.php';
if(isset($_POST['submit']))
{
$FName = mysqli_real_escape_string($conn, $_POST['First_Name']);
$LName = mysqli_real_escape_string($conn, $_POST['Last_Name']);
$Email = mysqli_real_escape_string($conn, $_POST['Email']);
$UName = mysqli_real_escape_string($conn, $_POST['User_Name']);
$Password = mysqli_real_escape_string($conn, $_POST['Password']); // why did you need to repeat this all twice?
$sql = "SELECT * FROM tbl_Users WHERE Email='$Email'"; // ? didn't understand why you was asking for the Email using the Email...
$result = $conn->query($sql);
if(count($result) == 0)
{
$insert_sql = "INSERT INTO tbl_Users (First_Name,Last_Name,Email,User_Name,Password) VALUES ('$FName','$LName','$Email','$UName','$Password')";
if($conn->query($insert_sql)) // You forgot to query this
{
echo "Thank you for registering";
header('Location: index.php'); // lowercase i
exit; // you forgot this
}
}
else
{
echo "Sorry, that email already exists!";
}
$conn->close(); // you forgot this
}
?>
Hope this helps...

PHP application not saving data to MySQL database

I am creating my first Wordpress plugin and have been stumped for a couple of days. So far I am trying to just get my plugin to save data to the MySQL database on my localhost. When I enter info into the form it creates a new row, which auto increments, but does not pass any of the info that I have entered into the database.
I understand that I have to clean up a lot of this code before I use it but I am just starting and stumped on this particular issue.
Here is the relevant code;
dvi_customer_info.php file
<?php
require('database.php');
require('customer_info_functions.php');
if ($action == 'add_customer') {
$rep = $_POST['rep'];
$business = $_POST['business'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$name = $_POST['name'];
$email = $_POST['email'];
}
add_customer($rep, $business, $address, $phone, $name, $email);
include('dvi_customer_info_sheet.php');
customer_info_functions.php file
<?php
function add_customer($rep, $business, $address, $phone, $name, $email) {
global $db;
$query = "INSERT INTO customers
(repName, customerBusiness, customerAddress, customerPhone, customerName, customerEmail)
VALUES
('$rep', '$business', '$address', '$phone', '$name', '$email')";
$db->exec($query);
}
?>
dvi_customer_info_sheet.php file
<body>
<h1>Customer Info Sheet</h1>
<form action="dvi_customer_info.php" method="post" id="customer_info_sheet_form">
<input type="hidden" name="action" value="add_customer" />
<label>Name of Rep:</label>
<input type="input" name="rep" />
<br />
<label>Name of Business:</label>
<input type="input" name="business" />
<br />
<label>Address:</label>
<input type="input" name="address" />
<br />
<label>Phone #:</label>
<input type="input" name="phone" />
<br />
<label>Name of Decision Maker:</label>
<input type="input" name="name" />
<br />
<label>Email:</label>
<input type="input" name="email" />
<br />
<label> </label>
<input type="submit" value="Add Customer" />
<br /> <br />
</form>
</body>
"INSERT INTO customers
(repName, customerBusiness, customerAddress, customerPhone, customerName, customerEmail)
VALUES
(\"$rep\", $business,...)
(Use double quotes "$rep" or don't use any quotes $business ( use this option) as anything within single quotes is taken as it is i.e a string constant and hence the variable inside that didn't get substituted by it's value
Try This
$query = "INSERT INTO customers
(repName, customerBusiness, customerAddress, customerPhone, customerName, customerEmail)
VALUES
('".$rep."', '".$business."', '".$address."', '".$phone."', '".$name."', '".$email."')";
And Also
I am not clear About your if condition if($action =='add_customer' ) instead of that try
if(isset($_POST['add_customer']))
What is $action?
you can use wordpress default action to insert record in to database like this below code it's sure to insert your record in mysql database.
You have no need to use function to just insert record in database just put this code in dvi_customer_info.php file
<?php
require('database.php');
require('customer_info_functions.php');
global $wpdb;
if ($action == 'add_customer') {
$rep = $_POST['rep'];
$business = $_POST['business'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$name = $_POST['name'];
$email = $_POST['email'];
$your_table_name_here = $wpdb->prefix . 'yourdatanase_table';
$data = array(
'repName' => $rep,
'customerBusiness' => $business,
'customerAddress' => $address,
'customerPhone' => $phone,
'customerName' => $name,
'customerEmail' => $email
);
$idsa = $wpdb->insert($your_table_name_here, $data);
if ($idsa) {
echo '<p class="alert-box success tfamsg">Franchise Setting Inserted.</p>';
}
}
include('dvi_customer_info_sheet.php');
?>
Now it will insert record in database you had also change your database table $your_table_name_here.
Thanks

Categories