Insert data from html form - php

im new to HTML and PHP. I am trying to create a form which loads my new users details into a database hosted by my web hosting company.
my form code (HTML) is :
<h1>Create Your GoSense Account</h1>
<form method:"POST" action:"newuserform.php" >
<div class="namef">
Name: <input type="text" style="width:200px" name="Name"
placeholder="First Name"><br></br> </div>
<div class="surnamef">
Surname: <input type="text" style="width:178px" name="Surname"
placeholder="Last Name"><br></br></div>
<div class="emailf">
Email: <input type="text" style="width:202px" name="Email"
placeholder="Email"><br></br> </div>
<div class="passwordf">
Password: <input type="text" style="width:170px" name="Password"
placeholder="Password"><br></br></div>
<input type="submit" style="font-size: 300px" name=""
value="Submit">
</form>
my PHP code stored in newuserform.php is:
<?php
define('DB_NAME','gosensec_useraccounts');
define('DB_USER','MyUsername');
define('DB_PASSWORD','myPassword');
define('DB_HOST','***.**.**.**');
$Name = filter_input(INPUT_POST,'Name');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
$db_selected = mysql_select_db (DB_NAME, $link) ;
$VALUE = $_POST['Name'];
$VALUE = $_POST['Surname'];
$VALUE = $_POST['Email'];
$VALUE = $_POST['Password'];
$sql = " INSERT INTO Users (Name) VALUES ('$VALUE')";
$sql = " INSERT INTO Users (Surname) VALUES ('$VALUE')";
$sql = " INSERT INTO Users (Email) VALUES ('$VALUE')";
$sql = " INSERT INTO Users (Password) VALUES ('$VALUE')";
mysql_close()
?>
I have doubled checked the connection parameters with my db host company and they advised that it is correct so my next step is to question my code ? Can anyone pick any errors that could be causing the data to insert into my DB ?
Many Thanks

There are multiple mistakes.
1- Assign each variable to a specific name:
$Name = $_POST['Name'];
$Surname = $_POST['Surname'];
$Email = $_POST['Email'];
$Password = $_POST['Password'];
2- insert all values into a single row not multiple rows.Also concatnate the variables as variables not as strings inside quotes!
$sql = "INSERT INTO Users (Name,Surname,Email,Password) VALUES ('" .$Name. "','". $Surname ."','". $Email ."','" .$Password. "')";
3- Do not forget to execute sql command:
$link->query($sql)
4- To close the connection use mysql_close($link)
finally: Do not forget to prevent SQL INJECTION by filtering values. Also try mysqli instead of the discontinued mysql API.

Related

Register Form PHP not inserting values into DB, just reloading the page

I really can not find what am I doing wrong in my registration form, unfortunately the page is just reloading instead of inserting values from form to my DB table.
Register.php
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}
}
?>
Connection.php
<?php
$conn = mysqli_connect("localhost","root","","KBHestate");
if(!$conn){
die("Connection error: " . mysqli_connect_error());
}
Register Form
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="firstName" value="" placeholder="First Name">
<input type="text" name="lastName" value="" placeholder="Surname">
<input type="text" name="email" value="" placeholder="Email">
<input type="text" name="phone" value="" placeholder="Phone">
<input type="password" name="password" value="" placeholder="Password">
<button type="submit" name="submit">Submit</button>
</form>
Please make sure the following line has no problem when it is interpreted by the PHP:
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
On the other hand, please make sure that the password field is wide enough to store the $hasPassword data
Your code looks fine, it should work. I am hoping you are having Register form in the same file Register.php
But as you mentioned it's just reload the page that means there must be a exception/error from mysql query that is not handled in your code.
You have not shared your table structure. So, I am answering you based on the common mistake.
Like one of your table column width is varchar(10) and you are trying to pass data of length 20 char.
So, i suggest you to add below code in your Register.php as the else condition for if($result). So, it will display the error if any.
else {
echo("Error description: " . $conn->error);
}
Now your Register.php code will be look like below:
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}else {
echo("Error description: " . $conn->error);
}
}
?>

Saving information to mysql table

So I want to create an html form and save it to a databas in WordPress
First I created the form which I put on this page here
<form action="addperson.php" method="post">
<label>First Name:</label>
<input type="text" name="firstname"/><br>
<label>Last Name:</label>
<input type="text" name="lastname"/><br>
<label>Email:</label>
<input type="text" name="email"/><br>
<input type="submit" name=submit value="Submit"/>
</form>
Then, in public html-->wp-content-my theme I created a file called addperson.php
In this file I put the following code :
<?php
//Block 1
$user = "user"; //Enter the user name
$password = "password"; //Enter the password
$host = "host"; //Enter the host
$dbase = "database"; //Enter the database
$table = "table"; //Enter the table name
//Block 2
$firstname= $_POST['firstname_entered'];
$lastname= $_POST['lastname_entered'];
$email= $_POST['email_entered'];
//Block 3
$connection= mysql_connect ($host, $user, $password);
if (!$connection){
die ('Could not connect:' .
mysql_error());
}
mysql_select_db($database, $connection);
//Block 4
$username_table= mysql_query( "SELECT username FROM $table WHERE username= '$username'" ) or die("SELECT Error: ".mysql_error());
//Block 5
mysql_query("INSERT INTO $table (column1, column2, column3) VALUES (value1, value2, value 3)");
//Block 6
echo 'You have been added.';
//Block 7
mysql_close($connection);
?>
Then I created a database and a table email_list like so:
CREATE TABLE IF NOT EXISTS
email_list (first_name VARCHAR(50),
last_name VARCHAR(50), email VARCHAR
(50));
Next, I entered info into formhere
It saved absolutely nothing.
Where am I going wrong?
Look at your HTML.
<input type="text" name="firstname"/>
<input type="text" name="lastname"/>
<input type="text" name="email"/>
And after submiting form, that data will be under firstname, lastname, email keys in $_POST array.
So you probably should change this
$firstname = $_POST['firstname_entered'];
$lastname = $_POST['lastname_entered'];
$email = $_POST['email_entered'];
to this
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
You should also consider enabling errors displaying in php to get more info about your potentials mistakes.
// Put this on top of your php file
ini_set('display_errors', '1');

Row being added to MySQL database but no other data from the html form using PHP

The data from the form is not getting saved into the database but a row is being added, I am hosting with Go Daddy. It worked perfectly on my local but now live seems to be not working. Please find below the code I am using:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$fName = mysql_real_escape_string($_POST['fName']);
$surname = mysql_real_escape_string($_POST['surname']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$tel = mysql_real_escape_string($_POST['tel']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$email = mysql_real_escape_string($_POST['email']);
$bool = true;
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db name", $con);
$sql="INSERT INTO customer (custNo, fName, surname, postcode, tel, mobile, email, timestamp)
VALUES (NULL, '$fName','$surname','$postcode', '$tel', '$mobile', '$email', 'CURRENT_TIMESTAMP')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
} else{
echo "Successfully Registered ";
}
}
mysql_close($con)
?>
and here is the html form
<form action="insert.php" method = "post">
<fieldset>
<legend>Register</legend>
<div class="col-md-4">
<label for='fName'>Enter name:</label>
<input type= "text" name = "fName" required="required" maxlength="50"/> <br/>
</div>
<div class="col-md-4">
<label for='surname'>Enter surname:</label>
<input type= "text" name="surname" maxlength="50" required="required"/> <br/>
</div>
<div class="col-md-4">
<label for='postcode'>Enter postcode:</label>
<input type= "text" name="postcode" maxlength="7"/> <br/>
</div>
<div class="col-md-4">
<label for='tel'>Enter home no:</label>
<input type= "text" name="tel" maxlength="50" /> <br/>
</div>
<div class="col-md-4">
<label for='mobile'>Enter mobile no:</label>
<input type= "text" name="mobile" maxlength="50"/> <br/>
</div>
<div class="col-md-4">
<label for='email'>Enter email * </label>
<input type= "text" name="email" required="required"/> <br/></br>
</div>
<input type="submit" value="Register"/>
</fieldset>
</form>
First :
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
If you didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);
This means the query sent to MySQL would be:
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
This would allow anyone to log in without a valid password.
To your problem !
All your variables are empty due to this fact ...
A MySQL connection is required before using mysql_real_escape_string()
otherwise an error of level E_WARNING is generated, and FALSE is
returned.
put your mysql_real_escape_string() after connect.
$con = mysql_connect("localhost","username","password");
if (!$con) { ...}
mysql_select_db("db name", $con);
//-------------- next after connect not before !!! --------
$fName = mysql_real_escape_string($_POST['fName']);
[...]
$email = mysql_real_escape_string($_POST['email']);
$bool = true;
$sql="INSERT INTO customer (...) VALUES (...)";
It may be due to the varibales.
try changing the $sql line to this
$sql = "INSERT INTO customer (custNo, fName, surname, postcode, tel, mobile, email, timestamp) VALUES (NULL, '" . $fName . "', '" . $surname . "', '" . $postcode . "', '" . $tel . "', '". $mobile . "', '" . $email . "', 'CURRENT_TIMESTAMP')";

Error when trying to Inserting into data into the database. Simple form

I'm new to PHP I have put together a simple form to input data into a database but the data doesn't seem to be inserting into the database. I've been trying to get it working all day.
shows the error Error to Inserting into database at the end of the code.
html
<div id="wrapper">
<section id="top_area">
<article class="box-right">
<form action="script/data.php" method="post">
<p>
<label>Company Name:</label>
<input name="company_name" required="required" placeholder="Joes Cleaners" type="text">
</p>
<p>
<label>Ref:</label>
<input name="ref_num" required="required" placeholder="D123" type="text">
</p>
<p>
<label>Website:</label>
<input name="website" required="required" placeholder="joescleaner.co.uk" type="text">
</p>
<p>
<label>Email:</label>
<input name="email" required="required" placeholder="joescleanersm#gmail.com" type="email">
</p>
<p>
<label>Telephone:</label>
<input name="tel" required="required" placeholder="0712345678" type="number">
</p>
<p>
<label>Message:</label>
<input name="message" required="required" placeholder="hello" type="text">
</p>
<p>
<input value="Submit" type="submit">
</p>
</form>
</article>
</section>
</div>
PHP
<?php
$db_hostname = 'localhost';
$db_database = 'form';
$db_username = 'user';
$db_password = 'password';
// Connect to server.
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());
// Select the database.
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
// Select the database.
mysql_select_db("form")
or die("Unable to select database: " . mysql_error());
// Get values from form
$company_name = $_POST['company_name'];
$ref_num = $_POST['ref_num'];
$website = $_POST['website'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];
// Insert data into mysql
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message)
VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message, NOW())";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
header('Location: ../thankyou.php');
}
else {
echo "Error to Inserting into database";
}
// close mysql
mysql_close();
?>
You should start using PDO for DB access, mysql_query is deprecated.
PDO let's you make prepared statements. These are secured against SQL Injections (your code isn't).
$stmt = $dbh->prepare("INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES (:company_name, :ref_num, :website, :email, :tel, :message, NOW())");
$stmt->bindParam(':company_name', $company_name);
$stmt->bindParam(':ref_num', $ref_num);
// And bind the remaining parameters
[...]
$stmt->execute();
If this fails, you can get detailed informations by running
print_r($stmt->errorInfo());
That should help you with finding errors in your SQL.
$dbh is a new PDO instance (see PDO::__construct)
As in your query you are trying to insert more than column values.
Your query is :
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message, NOW())"
Either remove NOW() data or add another column for NOW() data
Also you can try below query.
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message)"
When fixed column errors like Programming Student says, you should modify your mysql_query command:
it needs the db connection you opened before.
Try this:
$result = mysql_query($db_server, $sql);
Why don't try Object Oriented syntax ?
if ($db_server->query($sql) === TRUE) {
header('Location: ../thankyou.php'); } else {
echo "Error: " . $conn->error;
}
}

Added database rows are empty mysql/php

I want to write from my form to my database. I'm confused because this resembles the scripts from tutorials and there it works.
Form (w3schools example) extract:
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
php:
<?php
$con=mysqli_connect("localhost","XXX","AAA","databasename");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$age = mysqli_real_escape_string($_POST['age']);
$sql="INSERT INTO test (firstname, lastname, age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
This adds a new row to my database with each submission. The problem: this added row is empty, except for the age column which is always 0, regardless of what I submit.
Where is my mistake?
Refer to php document you must give two values to mysqli_real_escape_string.
try this:
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);

Categories