I have created a simple form that currently submits to a database. I am now wanting to add validation so that each field is required to be filled in.
This is what i have so far:
<?php include("header.php"); ?>
</br>
<form method = "post" action = "post-poster.php">
<label>Address Line 1:</label> <input name="addline1" id="addline1"></br>
<label>Area:</label> <input name="area" id="area"></br>
<label>Description:</label> <input name="description" id="description"></br>
<label>Bedrooms: </label><input name="bedrooms" id="bedrooms"></br>
<label>Bathrooms:</label> <input name="bathrooms" id="bathrooms"></br>
<label>Landlords Name:</label> <input name="lname" id="lname"></br>
<label>Landlords Number:</label> <input name="lphone" id="lphone"></br>
<label>Landlords Email:</label> <input name="lemail" id="lemail"></br>
</br>
<input type="submit" value="Submit">
</form>
<?php include("footer.php"); ?>
and this is the file that submits to the DB, i have blanked my db details:
<?php
/*
Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password)
*/
$link = mysqli_connect("localhost", "inspire_****", "*****", "inspire_****");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$addline1 = mysqli_real_escape_string($link, $_POST['addline1']);
$area = mysqli_real_escape_string($link, $_POST['area']);
$description = mysqli_real_escape_string($link, $_POST['description']);
$bedrooms = mysqli_real_escape_string($link, $_POST['bedrooms']);
$bathrooms = mysqli_real_escape_string($link, $_POST['bathrooms']);
$lname = mysqli_real_escape_string($link, $_POST['lname']);
$lphone = mysqli_real_escape_string($link, $_POST['lphone']);
$lemail = mysqli_real_escape_string($link, $_POST['lemail']);
// attempt insert query execution
$sql = "INSERT INTO posts (addline1, area, description, bedrooms, bathrooms, lname, lphone, lemail) VALUES ('$addline1', '$area', '$description', '$bedrooms', '$bathrooms', '$lname', '$lphone', '$lemail')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
If anyone can help me i would be greatly appreciated
One way, perhaps the lazy way, is to add required to each input tag. For example
<input name="addline1" id="addline1" required>
You can add the key word required in this manner to all input tags that apply.
Related
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);
}
}
?>
I've been racking my brains over this problem for a while now but as yet have not found the problem. I have a form (in index.php) that uploads the user input to a database after the submit button is pressed. As expected I'm redirected to add_records.php after pressing submit, but then I'm stuck on it, despite including the line
header("location: index.php")
The redirect works fine if I comment out all the mysqli code, therefore I've concluded the error is to do with mysqli and uploading to the database (perhaps I'm handling the geographical data incorrectly). I've done all the usual things - checked the error log, checked for any errors on PHPMyAdmin but all show no errors! I shown the code below to help troubleshoot, with all sensitive info replaced with '#' (note - I've checked the database password etc. several times and they're correct).
index.php:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: ##/records/login.php");
exit;
}
echo file_get_contents("##/code/header.php");
?>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
</div>
<form action="##/records/add_records.php" method="POST">
<input type="text" name="species" placeholder="Species">
<br>
<input type="date" name="date" placeholder="Date">
<br>
<input type="time" name="time" placeholder="Time">
<br>
<input type="location" name="location" placeholder="Location Name">
<br>
<input type="text" name="lat/long" placeholder="Lat Long">
<br>
<input type="number" name="count" placeholder="Count">
<br>
<input type="text" name="county" placeholder="County (default Norfolk)">
<br>
<input type="text" name="country" placeholder="Country (default United Kingdom)">
<br>
<input type="text" name="notes" placeholder="Notes">
<br>
<button type="submit" name="submit">Submit</button>
</form>
<p>
Sign Out of Your Account
</p>
<?php echo file_get_contents("##/code/footer.php"); ?>
add_records.php:
<?php include_once '##/records/config_bird_records.php';
$species = mysqli_real_escape_string($conn, $_POST['species']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$time = mysqli_real_escape_string($conn, $_POST['time']);
$location = mysqli_real_escape_string($conn, $_POST['location']);
$latlong = mysqli_real_escape_string($conn, $_POST['latlong']);
$count = mysqli_real_escape_string($conn, $_POST['count']);
$county = mysqli_real_escape_string($conn, $_POST['county']);
$country = mysqli_real_escape_string($conn, $_POST['country']);
$notes = mysqli_real_escape_string($conn, $_POST['notes']);
$sql = "INSERT INTO bird_db (Species, Date, Time, Location, Lat/Long, Count, County, Country, Notes) VALUES ('$species', $date, $time, '$location', geography::STGeomFromText('POINT($latlong)', 4326), $count, '$county', '$country', '$notes')";
mysqli_query($conn, $sql);
mysqli_close($conn);
header("location: ##/records/index.php")
?>
config_bird_records.php:
<?php
/* Database credentials.*/
define('DB_SERVER', '##');
define('DB_USERNAME', '##');
define('DB_PASSWORD', '##');
define('DB_NAME', '##');
/* Attempt to connect to MySQL database */
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Thanks for any help,
Louis
The header method needs to be called before you send any output to the browser.
Your code includes output in both success and error cases, which means the redirect will never work. If you remove echo "Records added successfully."; it should work.
you can use javascript for that instead of header() fro redirecting; function
try the following:
echo "<script type='text/javascript'>alert('Upload Successful');
window.location='redirected_page.php';
</script>";
As for the failing to upload, have you googled how mysqli_real_escape_string works, u need to because it will affect some special characters in you variables
When I press the submit button I get error.
object not found error.
And the page automatically adds empty entries with auto incremented primary key (without pressing the submit button).
I am still a beginner in PHP, I searched thoroughly but I can't find out what's wrong in code.
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="Name">Full Name:</label>
<input type="text" name="Name" id="Name">
</p>
<p>
<label for="Code">Code:</label>
<input type="text" name="Code" id="Code">
</p>
<p>
<label for="GPA">GPA:</label>
<input type="text" name="GPA" id="GPA">
</p>
<input type="submit" value="Submit">
</form>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "username", "password", "students");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$full_name = filter_input(INPUT_POST, 'full_name');
$code = filter_input(INPUT_POST, 'code');
$gpa = filter_input(INPUT_POST, 'gpa');
// attempt insert query execution
$sql = "INSERT INTO info VALUES ('$full_name', '$code', '$gpa')";
if (mysqli_query($link, $sql)) {
echo "Records added successfully. $full_name";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
</body>
</html>
Try this:
$full_name = filter_input(INPUT_POST, 'Name');
$code = filter_input(INPUT_POST, 'Code');
$gpa = filter_input(INPUT_POST, 'GPA');
The reason why I wrote that is because your input names contain Name, Code and GPA so you need to write this exactly as your input names (case-sensitive).
Do with isset(). when the submit button clicks only the code runs.
Inside the php you should use the form input name field.
<?php
if(isset($_POST['submit'])){
$link = mysqli_connect("localhost", "username", "password", "students");
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$full_name = filter_input(INPUT_POST, 'full_name');
$code = filter_input(INPUT_POST, 'code');
$gpa = filter_input(INPUT_POST, 'gpa');
//to prevent sql injection attack
$full_name = mysqli_real_escape_string($link, $full_name);
$code = mysqli_real_escape_string($link, $code);
$gpa = mysqli_real_escape_string($link, $gpa);
// attempt insert query execution
$sql = "INSERT INTO info (Name,Code,GPA) VALUES ('$full_name', '$code', '$gpa')";
if (mysqli_query($link, $sql)) {
echo "Records added successfully. $full_name";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
?>
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="Name">Full Name:</label>
<input type="text" name="full_name" id="Name">
</p>
<p>
<label for="Code">Code:</label>
<input type="text" name="code" id="Code">
</p>
<p>
<label for="GPA">GPA:</label>
<input type="text" name="gpa" id="GPA">
</p>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
The problem is the input name. You named Full Name input with name="Name", but you declare $full_name = filter_input(INPUT_POST, 'full_name'); in php section. you must change full_name to Name. As well as the Code and GPA input.
I am fairly new to PHP and I was following a simple tutorial on youtube, I followed the youtube video, double and tripple checked to make sure everything I typed was correct and data was still not being inserted.
I searched the internet for hours and I came up with a fix, sort of but I don't think it's the correct way to do it
HTML
<html>
<head>
<title>Insert Form Data In MYSQL Database Using PHP</title>
</head>
<body>
<form action="insert.php" method="post">
Name : <input type="text" name="username">
<br/>
Email : <input type="text" name="email">
<br/>
<input type="submit" value="Insert">
</form>
</body>
</html>
PHP
<?php
$con = mysqli_connect('localhost','root','');
if (!$con) {
echo 'Not Connected To Server';
}
if (!mysqli_select_db($con,'tutorial')) {
echo 'Database Not Selected';
}
if (isset($_POST['username'])){
$Name = $_POST['username'];
}
if (isset($_POST['email'])){
$Email = $_POST['email'];
}
$sql = "INSERT INTO person (Name, Email) VALUES ('John', 'john#gmail.com')";
if (!mysqli_query($con,$sql)) {
echo 'Not Inserted';
} else {
echo 'Inserted Successfully!';
}
header("refresh:10; url=index.html");
?>
I replaced '$Name' and '$Email' with John and john#gmail.com, then I type it into the html form and the data goes into the database correctly.
I then found another HTML form online with more PHP but it does the same thing(not inserting any data to the database)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert1.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
// attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
The fields are blank, any help will be greatly appreacited!
Btw This is how the fields display I'm using xampp server.
I had used the below code and it works fine for me.
<?php
$link = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
/* Collect below values from $_POST
$firstname = 'John';
$lastname = 'Doe';
$email = 'test#gmail.com';
*/
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $firstname);
$last_name = mysqli_real_escape_string($link, $lastname);
$email_address = mysqli_real_escape_string($link, $email);
// attempt insert query execution
$sql = "INSERT INTO accounts (account_firstname, account_lastname, account_email) VALUES ('$first_name', '$last_name', '$email_address')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
I want to insert and update customer data by clicking on insert and update button using functions but when I click on insert or update button no data is inserted or updated whats the problem with my code??
<form action="Customer.php" method="post">
<div>
<form>
Phone No <input type="number" placeholder="Search" name="phoneno" />
First Name <input type="text" name="FirstName" />
Last Name<input type="text" name="LastName" />
Phone No<input type="number" name="CustomerPhoneNo" />
Address<input type="text" name="Address" />
Customer ID<input type="number" name="CustomerID" />
<input type="Submit" value="Add Customer" style="font-size:20px" onClick="insert()">
<input type="Submit" value="Update Customer" style="font-size:20px" onClick="update()">
</form>
</div>
"Customer.php"
<?php
$dbhost="127.0.0.1";
$dbname="root";
$dbuser="info";
$dbpsd="";
$link = mysqli_connect("$dbhost", "$dbuser", "$dbpsd", "$dbname");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$phoneno = mysqli_real_escape_string($link, $_POST['phoneno']);
$FirstName = mysqli_real_escape_string($link, $_POST['FirstName']);
$LastName = mysqli_real_escape_string($link, $_POST['LastName']);
$CustomerPhoneNo = mysqli_real_escape_string($link, $_POST['CustomerPhoneNo']);
$Address=mysqli_real_escape_string($link, $_POST['Address']);
$CustomerID = mysqli_real_escape_string($link, $_POST['CustomerID']);
function insert(){
$sql = "INSERT INTO clientinfo(phoneno, FirstName, LastName,CustomerPhoneNo,Address,CustomerID) VALUES ('$phoneno', '$FirstName', '$LastName','$CustomerPhoneNo','$Address','$CustomerID')";
echo "<span>Data Inserted successfully...!!</span>";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
function update(){
$sql="UPDATE clientinfo SET FirstName='$FirstName', LastName='$LastName',Address='$Address',CustomerID='$CustomerID WHERE phoneno='$phoneno' ";
if (mysqli_query($link, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($link);
}
}
close connection
mysqli_close($link);
?>
you can't use onclick tag to determine of requested page PHP function .
a easy way to do it . replace below codes at the customer.php file.
Replace :
function insert()
with :
if($_POST['Submit'] == 'Add Customer')
and replace :
function update()
with :
if($_POST['Submit'] == 'Update Customer')
Try this:
Delete the second tag and put the first one in that place.
Other thing, is that you need to review the code.
Review this Tutorial
PHP Tutorial
You are calling php function like js functions. They dont work like that. Define them like -
function insert($link, $post){
$phoneno = mysqli_real_escape_string($link, $post['phoneno']);
$FirstName = mysqli_real_escape_string($link, $post['FirstName']);
$LastName = mysqli_real_escape_string($link, $post['LastName']);
$CustomerPhoneNo = mysqli_real_escape_string($link, $post['CustomerPhoneNo']);
$Address=mysqli_real_escape_string($link, $post['Address']);
$CustomerID = mysqli_real_escape_string($link, $post['CustomerID']);
$sql = "INSERT INTO clientinfo(phoneno, FirstName, LastName,CustomerPhoneNo,Address,CustomerID) VALUES ('$phoneno', '$FirstName', '$LastName','$CustomerPhoneNo','$Address','$CustomerID')";
echo "<span>Data Inserted successfully...!!</span>";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
And cal them like -
insert($link, $_POST); // if it is inserting