Populate database with data from a form - php

I want to fill all the fields in my database by getting the ones inputted on my form but it won't fill my database.
I don't know what's wrong with it:
<?php
$handle = mysql_connect("", "root" , "");
return mysql_select_db("bonggarden", $handle);
$SQL = "INSERT INTO table1(fname,femail,fphone,fmsg)
values('".$_POST['name']."','".$_POST['email']."','".$_POST['number']."','".$_PO ST['message']."')";
mysql_query($SQL);
?>
here is my form
<form id="main-contact-form" accept-charset="utf-8" class="" method="post" >
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>Name *</label>
<input type="text" name="name" id="name" class="form-control" required="required">
</div>
<div class="form-group">
<label>Email *</label>
<input type="email" name="email" id="email" class="form-control" required="required">
</div>
<div class="form-group">
<label>Phone *</label>
<input type="text" name="number" id="number" class="form-control">
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label>Message *</label>
<textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>
</div>
<div class="form-group">
<button type="submit" name="submit" class="btn btn-primary btn-lg" required="required">Submit Message</button>
</div>
</div>
</form>

<?php
$fname = $_POST['name'];
$femail = $_POST['email'];
$fphone = $_POST['number'];
$fmsg = $_POST['message'];
$handle = mysql_connect("localhost", "root" , "");
mysql_select_db("bonggarden", $handle);
$SQL = "INSERT INTO table1(fname,femail,fphone,fmsg) values('$fname','$femail','$fphone','$fmsg')";
mysql_query($SQL);
?>
// if it still not working echo the variable $fname, $femail, $fphone, $fmsg check value is proparly getting in veriable or not.

Try changing
return mysql_select_db("bonggarden", $handle);
to
mysql_select_db("bonggarden", $handle);
The return is exiting the code before you execute the insert...

You do not need the 'return' in:
return mysql_select_db("bonggarden", $handle);
You may also consider adding the location of your server to your 'mysql_connect' function. EX:
mysql_connect("localhost","root","");
A couple of suggestions too:
1.) Organizationally, assigning your values from $_POST to variables might make it easier to see what values you are sending to your database.
2.) Add a die function that outputs a MySQL error if your code cannot be run. This can often help with debugging and finding out the general location of your error. EX:
mysql_query($SQL) or die(mysql_error());
3.) Finally, and this gets said a lot on this website, consider switching to MySQLi as traditional 'mysql_' commands are now deprecated for security reasons.

Related

PHP form submit loads blank page?

I am aware there are a lot of questions on this regarding this issue, but I have looked through them all and none of the solutions seem to fix the issue for me. I have a form that when submitted, posts the data and it is retrieved via if(isset), as far as I know, all the syntax is correct, and the name attributes of the inputs are correct.
When I submit the form, the data in the form gets inserted into a mysql database, which works, the only issue is the blank page. Here is the php code at the top of the page and the relative html code.
PHP
<?php
require('connection.php');
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$body = $_POST['message'];
try {
$stmt = $db->prepare("INSERT INTO `contact` (`c_name`, `c_email`, `c_number`, `c_body`) VALUES (:name, :email, :num, :body)");
$stmt->execute(array(':name' => $name, ':email' => $email, ':num' => $number, ':body' => $body));
return $stmt;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
HTML
<form method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="name" class="form-control" id="name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" name="number" class="form-control" id="number">
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea name="message" class="form-control" id="message" rows="6"></textarea>
</div>
<input type="submit" name="submit" class="btn btn-primary" />
</form>

Why is the header not working in this code?

The php code to get to the header after executing the queries
<?php
if (isset($_POST['Submit1'])) {
$con = mysqli_connect("localhost:3306", "root", "", "travels");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$fname1 = $_POST['fname'];
$lname1 = $_POST['lname'];
$pnum1 = $_POST['pnum'];
$email1 = $_POST['email'];
$fcode = $_POST['fcode'];
$sql = "insert into customer_info(fname,lname,pnumber,email) values ('$fname1','$lname1','$pnum1','$email1')";
$sql1 = "insert into booking_info(fname,lname,pnumber,email,f_code) values ('$fname1','$lname1','$pnum1','$email1','$fcode')";
$sql2 = "update flight_info set seats_available=seats_available-1 where flight_code='$fcode'";
mysqli_query($con, $sql);
mysqli_query($con, $sql1);
mysqli_query($con, $sql2);
header("Location: Booking_confirm.php");
}
?>
HTML CODE
<div class="container mt-5">
<div class="row">
<div class="col-md-6">
<form action="Booking.php" method="POST">
<div class="form-group">
<label for="fname">First Name: </label>
<input type="text" name="fname" class="form-control" id="fname"/>
</div>
<div class="form-group">
<label for="lname">Last Name: </label>
<input type="text" name="lname" class="form-control" id="lname"/>
</div>
<div class="form-group">
<label for="pnum">Phone Number: </label>
<input type="text" name="pnum" class="form-control" id="pnum"/>
</div>
<div class="form-group">
<label for="email">Email-Address: </label>
<input type="text" name="email" class="form-control" id="email"/>
</div>
<div class="form-group">
<label for="flight">Flight No: </label>
<input type="text" name="fcode" class="form-control" id="fcode"/>
</div>
<form action="Booking_confirm.php" method="POST" target="_blank">
<button type="Submit" name="Submit1" class="btn btn-primary">Book</button>
</form>
</form>
</div>
This is how my code looks. for some reason my header is not working and i am not able to find out why.
Help would be appreciated.
I have tried every possible change to get the header to work but of no use
You have two nested forms, your first form action="Booking.php" contains all fields while the second, nested form action="Booking_confirm.php", only contains the submit button an NO fields.
Replace
<form action="Booking_confirm.php" method="POST" target="_blank">
<button type="Submit" name="Submit1" class="btn btn-primary">Book</button>
</form>
with
<button type="Submit" name="Submit1" class="btn btn-primary">Book</button>
When clicking submit there is no $_POST['fname'], $_POST['lname'] etc.
Edit: you also might need to replace
<form action="Booking.php" method="POST">
with
<form action="Booking_confirm.php" method="POST" target="_blank">
depending on where your "header"/code is placed
Make sure there is not white space or html tags or any output, before the header() function...
upload the entire code, structure so we can help you find the solution

User register is successful, however the data is not stored in database without showing any error

Sorry if what I'm going to ask is a dumb question, but I have read through and even apply some of the solutions to my problem but it's still not working. I've got the solutions from here:
1. Not Getting response after registration is successful
2. php register form not updating database
3. Inserted data was not saved during registration
I have a system where the user can register himself/herself as a candidate for job interviews. But right now, the system doesn't save their registration. I have go through the queries but find nothing. Perhaps anybody can point out where I have been doing wrong that make my system doesn't want to keep the data.
my register-candidates.php
<section class="content-header">
<div class="container">
<div class="row latest-job margin-top-50 margin-bottom-20 bg-white">
<h1 class="text-center margin-bottom-20">CREATE YOUR PROFILE</h1>
<form method="post" id="registerCandidates" action="adduser.php" enctype="multipart/form-data">
<div class="col-md-6 latest-job ">
<div class="form-group">
<input class="form-control input-lg" type="text" id="fname" name="fname" placeholder="First Name *" required>
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="lname" name="lname" placeholder="Last Name *" required>
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="email" name="email" placeholder="Email *" required>
</div>
<div class="form-group">
<textarea class="form-control input-lg" rows="4" id="aboutme" name="aboutme" placeholder="Brief intro about yourself *" required></textarea>
</div>
<div class="form-group">
<label>Date Of Birth</label>
<input class="form-control input-lg" type="date" id="dob" min="1960-01-01" max="1999-01-31" name="dob" placeholder="Date Of Birth">
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="age" name="age" placeholder="Age" readonly>
</div>
<div class="form-group">
<label>Passing Year</label>
<input class="form-control input-lg" type="date" id="passingyear" name="passingyear" placeholder="Passing Year">
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="qualification" name="qualification" placeholder="Highest Qualification">
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="stream" name="stream" placeholder="Stream">
</div>
<div class="form-group checkbox">
<label><input type="checkbox"> I accept terms & conditions</label>
</div>
<div class="form-group">
<button class="btn btn-flat btn-success">Register</button>
</div>
<?php
//If User already registered with this email then show error message.
if(isset($_SESSION['registerError'])) {
?>
<div class="form-group">
<label style="color: red;">Email Already Exists! Choose A Different Email!</label>
</div>
<?php
unset($_SESSION['registerError']); }
?>
<?php if(isset($_SESSION['uploadError'])) { ?>
<div class="form-group">
<label style="color: red;"><?php echo $_SESSION['uploadError']; ?></label>
</div>
<?php unset($_SESSION['uploadError']); } ?>
</div>
<div class="col-md-6 latest-job ">
<div class="form-group">
<input class="form-control input-lg" type="password" id="password" name="password" placeholder="Password *" required>
</div>
<div class="form-group">
<input class="form-control input-lg" type="password" id="cpassword" name="cpassword" placeholder="Confirm Password *" required>
</div>
<div id="passwordError" class="btn btn-flat btn-danger hide-me" >
Password Mismatch!!
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="contactno" name="contactno" minlength="10" maxlength="10" onkeypress="return validatePhone(event);" placeholder="Phone Number">
</div>
<div class="form-group">
<textarea class="form-control input-lg" rows="4" id="address" name="address" placeholder="Address"></textarea>
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="city" name="city" placeholder="City">
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="state" name="state" placeholder="State">
</div>
<div class="form-group">
<textarea class="form-control input-lg" rows="4" id="skills" name="skills" placeholder="Enter Skills"></textarea>
</div>
<div class="form-group">
<input class="form-control input-lg" type="text" id="designation" name="designation" placeholder="Designation">
</div>
<div class="form-group">
<label style="color: red;">File Format PDF Only!</label>
<input type="file" name="resume" class="btn btn-flat btn-danger" required>
</div>
</div>
</form>
</div>
</div>
</section>
adduser.php
<?php
//To Handle Session Variables on This Page
session_start();
//Including Database Connection From db.php file to avoid rewriting in all files
require_once("db.php");
//If user clicked register button
if(isset($_POST)) {
//Escape Special Characters In String First
$firstname = mysqli_real_escape_string($conn, $_POST['fname']);
$lastname = mysqli_real_escape_string($conn, $_POST['lname']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$city = mysqli_real_escape_string($conn, $_POST ['city']);
$state = mysqli_real_escape_string($conn, $_POST ['state']);
$contactno = mysqli_real_escape_string($conn, $_POST ['contactno']);
$qualification = mysqli_real_escape_string($conn, $_POST ['qualification']);
$stream = mysqli_real_escape_string ($conn, $_POST['stream']);
$passingyear = mysqli_real_escape_string($conn, $_POST['passingyear']);
$dob = mysqli_real_escape_string($conn, $_POST['dob']);
$age = mysqli_real_escape_string($conn, $_POST['age']);
$designation = mysqli_real_escape_string($conn, $_POST['designation']);
$aboutme = mysqli_real_escape_string($conn, $_POST['aboutme']);
$skills = mysqli_real_escape_string($conn, $_POST['skills']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
//Encrypt Password
$password = base64_encode(strrev(md5($password)));
//sql query to check if email already exists or not
$sql = "SELECT email FROM users WHERE email='$email'";
$result = $conn->query($sql);
//if email not found then we can insert new data
if($result->num_rows == 0) {
//This variable is used to catch errors doing upload process. False means there is some error and we need to notify that user.
$uploadOk = true;
//Folder where you want to save your image. THIS FOLDER MUST BE CREATED BEFORE TRYING
$folder_dir = "uploads/resume/";
//Getting Basename of file. So if your file location is Documents/New Folder/myResume.pdf then base name will return myResume.pdf
$base = basename($_FILES['resume']['name']);
//This will get us extension of your file. So myimage.pdf will return pdf. If it was image.doc then this will return doc.
$imageFileType = pathinfo($base, PATHINFO_EXTENSION);
//Setting a random non repeatable file name. Uniqid will create a unique name based on current timestamp. We are using this because no two files can be of same name as it will overwrite.
$file = uniqid() . "." . $resumeFileType;
//This is where your files will be saved so in this case it will be uploads/image/newfilename
$filename = $folder_dir .$file;
//We check if file is saved to our temp location or not.
if(file_exists($_FILES['resume']['tmp_name'])) {
//Next we need to check if file type is of our allowed extention or not. I have only allowed pdf. You can allow doc, jpg etc.
if($resumeFileType == "pdf") {
//Next we need to check file size with our limit size. I have set the limit size to 5MB. Note if you set higher than 2MB then you must change your php.ini configuration and change upload_max_filesize and restart your server
if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB
//If all above condition are met then copy file from server temp location to uploads folder.
move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
} else {
//Size Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
$uploadOk = false;
}
} else {
//Format Error
$_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB ";
$uploadOk = false;
}
} else {
//File not copied to temp location error.
$_SESSION['uploadError'] = "Something Went Wrong. File Not Uploaded. Try Again.";
$uploadOk = false;
}
//If there is any error then redirect back.
if($uploadOk == false) {
header("Location: register-candidates.php");
exit();
}
//sql new registration insert query
$sql = "INSERT INTO users(firstname, lastname, email, password, address, city, state, contactno, qualification, stream, passingyear, dob, age, designation, resume, hash, aboutme, skills) VALUES ('$firstname', '$lastname', '$email', '$password', '$address', '$city', '$state', '$contactno', '$qualification', '$stream', '$passingyear', '$dob', '$age', '$designation', '$file', '$hash', '$aboutme', '$skills')";
if($conn->query($sql)===TRUE) {
//If data inserted successfully then Set some session variables for easy reference and redirect to company login
$_SESSION['registerCompleted'] = true;
header("Location: login-candidates.php");
exit();
} else {
//If data failed to insert then show that error. Note: This condition should not come unless we as a developer make mistake or someone tries to hack their way in and mess up :D
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
//if email found in database then show email already exists error.
$_SESSION['registerError'] = true;
header("Location: register-candidates.php");
exit();
}
//Close database connection. Not compulsory but good practice.
$conn->close();
} else {
//redirect them back to register page if they didn't click register button
header("Location: register-candidates.php");
exit();
}
thank you for the help and your time.
I think you should to debug your app by following those steps :
Try to direct insert data from SQL command in your ManagementInterface
Try to echo $var | var_dump($var) of each input you get from your form when you reach your register.php.
Try to see if you reach your condition like if(isset($_POST["var"]&&!empty($_POST["var"])) but if you can echo them it's not here you have to search
It might be your queries statement that block you.
You should try to improve your code with prepared statement for your SQL queries, it will be more readable and maintenable. Also, i think that mysqli & co are deprecated.
I hope it will be usefull for you and it ill help you to find your error.
Respond in comment if this doesn't help you, 'ill try to find out why
Regards
You have not defined $resumeFileType and in order for your script to execute, it has to check that the $resumeFileType is a PDF.

Submit goes to action page even without value

Every time I press submit. It goes straight to the (action) page without checking to see if any value is filled in.How do I stop it from changing pages without first checking to see if any information is filed in the name email and comment?
<?php
if( empty($name) && isset($_POST["submit"])){
global $connect;
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST["comment"];
$sql = "INSERT INTO entries (fullName,email,comment)
VALUES ('$name', '$email', '$comment')";
$result = mysqli_query($connect, $sql);
if(!$result){
die("try again" .mysqli_error());
}
}
?>
<section>
<div class="container text-center ">
<h1>Guess Book</h1>
<div class="row"></div>
<form class="text-center" action="thankYou.php" method="post" id="signUp" >
<label class="mb-2 mt-2" style="padding-right:1vh" for="name">Please Enter Your Full Name Here:</label><input type="text" name="name" placeholder="Enter Full Name" minlength="3" ><br>
<label class="mb-2 mt-2" style="padding-right:4.1vh" for="email">Please Enter Your Email Here:</label><input type="email" name="email" placeholder="Enter Email" minlength="4" ><br>
<div class="form-group ">
<label for="comment">Comment:</label>
<textarea name="comment" class="form-control mb-3" rows="8" minlength="4" id="comment"></textarea>
</div>
<input class="bottom-pad" type="submit" name="submit">
</form>
</div>
</section>
the simplest option is to use html "required" attribute
in your case:
<input type="text" name="name" placeholder="Enter Full Name" minlength="3" required>
this is client side validation, you also always need to validate server side.
your code:
if( empty($name) && isset($_POST["submit"])){
is slightly wrong, here is the fixed version
if( !empty($_POST['name']) && isset($_POST["submit"])){
The reason why it get submited , it because your not doing any validation in the form for a minimal validation you can use required on the input field
Please consider using a better validation i just used this for the purpose of demonstration
<section>
<div class="container text-center ">
<h1>Guess Book</h1>
<div class="row"></div>
<form class="text-center" action="thankYou.php" method="post" id="signUp" >
<label class="mb-2 mt-2" style="padding-right:1vh" for="name">Please Enter Your Full Name Here:</label><input type="text" name="name" placeholder="Enter Full Name" minlength="3" required><br>
<label class="mb-2 mt-2" style="padding-right:4.1vh" for="email">Please Enter Your Email Here:</label><input type="email" name="email" placeholder="Enter Email" minlength="4" required><br>
<div class="form-group ">
<label for="comment">Comment:</label>
<textarea name="comment" class="form-control mb-3" rows="8" minlength="4" id="comment" required></textarea>
</div>
<input class="bottom-pad" type="submit" name="submit">
</form>
</div>
</section>
You can do form validation like the previous answers have suggested. This will prevent the form from submitting unless the inputs that are required have a value in them.
You should also get in the habit of validating your code on the server side as well to make sure the data submitted by the user is the information you expect to be submitted by the user.
Here is some simple code to check to make sure that the values at least have something in them. You can take it further to validate that each field has data that meets certain criteria like a name only having alpha characters.
if($_POST["submit"] && isset($_POST["submit"])){
global $connect;
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST["comment"];
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["comment"])){
$sql = "INSERT INTO entries (fullName,email,comment)
VALUES ('$name', '$email', '$comment')";
$result = mysqli_query($connect, $sql);
if(!$result){
die("try again" .mysqli_error());
}
} else {
echo 'You must enter enter a value for all fields.';
}
}

An empty row getting inserted in database

Hey I am trying to get this code running for the past few days now. I do not know what is the problem. Whenever I run the code I can see it running but an empty row gets inserted. Basically I ave tried to hard code the data and the data gets inserted. Here is the HTML form:
<form action="register.php" id="contactForm" type="post">
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>First name *</label>
<input type="text" class="form-control" name="fname" >
</div>
<div class="col-md-6">
<label>Last name *</label>
<input type="text" class="form-control" name="lname" >
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>Gender *</label><br>
<select name="gender">
<option> Male </option>
<option> Female </option>
</select>
</div>
<div class="col-md-6">
<label>Stream *</label><br>
<select name="stream">
<option> B-Tech </option>
<option> M-Tech </option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>Email *</label>
<input type="text" class="form-control" name="email" >
</div>
<div class="col-md-6">
<label>Mobile *</label>
<input type="text" class="form-control" name="mobile">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>College *</label>
<input type="text" class="form-control" name="college" >
</div>
<div class="col-md-6">
<label>Job Kind *</label>
<input type="text" class="form-control" name="job" >
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
&nbsp&nbsp&nbsp&nbsp
<input type="submit" value="Register" class="btn btn-primary btn-lg"
data-loading-text="Loading..." name="submit">
</div>
</div>
</form>
Here is the registration.php
<?php
$connection = mysql_connect("EDITED by billy, was an I.P and port number", "user", "password"); // Establishing Connection with Server
$db = mysql_select_db("Registrations_connect", $connection); // Selecting Database from Server
$first_name = $_POST["fname"];
$last_name = $_POST["lname"];
$sex = $_POST["gender"];
$field = $_POST["stream"];
$contact = $_POST["mobile"];
$eaddress = $_POST["email"];
$institute = $_POST["college"];
$naukri = $_POST["job"];
$query = mysql_query("insert into students(fname, lname, gender, stream, mobile, email, college, job)
values ('$name', '$last_name', '$sex', '$field','$contact', '$eaddress', '$intitute', '$naukri')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
mysql_close($connection); // Closing Connection with Server
?>
After running; In the inspect element I checked the response:- It shows Data Inserted successfully but actually an empty row is getting inserted. Basically what i think I am not able to correctly grab the data properly from form. Can somebody please check what is the problem. It will be a great help.
The attribute is method, not type. This typo is causing your form to process a GET rather than a POST. So all your variable assignments are wrong.
$first_name = $_POST["fname"];
would be
$first_name = $_GET["fname"];
or you could use the $_REQUEST; or you can just correct the attribute,
<form action="register.php" id="contactForm" method="post">
Your code also is wide open to SQL injections and is using the deprecated mysql_ functions. You should update to mysqli or pdo and be using prepared statements with parameterized queries.
More on SQL injections:
http://php.net/manual/en/security.database.sql-injection.phpHow can I prevent SQL injection in PHP?https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_Queries.29

Categories