Send html form data to sql database via php - php

I'm attempting to insert the data collected on the form into a mysql database. I'm able to make a successful connection but the data is not inserted. I've read many similar questions but have been unsuccessful so far.
sqldatabase.php
<?php
$servername = "localhost";
$username = "USER";
$password = "PASS";
$dbname = "DATABASE";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$first_spouse = $_POST['first_spouse'];
$last_spouse = $_POST['last_spouse'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phonehome = $_POST['phonehome'];
$phonecell = $_POST['phonecell'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$occupation = $_POST['occupation'];
$shirt_size = $_POST['shirt_size'];
$cap_size = $_POST['cap_size'];
$shirtnum1 = $_POST['shirtnum1'];
$shirtnum2 = $_POST['shirtnum2'];
$desc = $_POST['desc'];
$bylaws_rules = $_POST['bylaws_rules'];
$umpires = $_POST['umpires'];
$alcohol = $_POST['alcohol'];
$waiver = $_POST['waiver'];
$sql="INSERT INTO 'softball_reg_2016' (first_name, last_name, first_spouse, last_spouse,
address, city, state, zip, phonehome, phonecell, email, dob, occupation, shirt_size,
cap_size, shirtnum1, shirtnum2, desc, bylaws_rules, umpires, alcohol, waiver)
VALUES ('$_POST[first_name]', '$_POST[last_name]', '$_POST[first_spouse]', '$_POST[last_spouse]',
'$_POST[address]', '$_POST[city]', '$_POST[city]', '$_POST[state]', '$_POST[zip]',
'$_POST[phonehome]', '$_POST[phonecell]', '$_POST[email]', '$_POST[dob]', '$_POST[occupation]',
'$_POST[shirt_size]', '$_POST[cap_size]', '$_POST[shirtnum1]', '$_POST[shirtnum2]',
'$_POST[desc]', '$_POST[bylaws_rules]', '$_POST[umpires]', '$_POST[alcohol]', '$_POST[waiver]')";
echo "Connected successfully";
mysqli_close($conn);
?>
My html
<form action="/php/sqldatabase.php" method="POST" id="registration">
<h2>Registration for 2016 Summer Season (April-September)</h2>
<p>
<label for="name">Name:</label>
<input type="text" id="first_name" name="first_name" placeholder="First Name" autofocus="" />
<input type="text" id="last_name" name="last_name" placeholder="Last Name" />
</p>
<p>
<label for="spouse">Name of Spouse<i>(Optional)</i>:</label>
<input type="text" id="first_spouse" name="first_spouse" placeholder="First Name" />
<input type="text" id="last_spouse" name="last_spouse" placeholder="Last Name" />
</p>
<p>
<label for="address1">Address:</label>
<input type="text" id="address" name="address" placeholder="Street Address" />
<input type="text" id="city" name="city" placeholder="City" />
</p>
<p>
<label for="address2"></label>
<input type="text" id="state" name="state" placeholder="State" />
<input type="number" id="zip" name="zip" placeholder="Zip Code" />
</p>
<p>
<label for="phone">Phone:</label>
<input type="tel" id="phonehome" name="phone" placeholder="Home Phone" />
<input type="tel" id="phonecell" name="phone" placeholder="Work/Cell Phone" />
</p>
<p>
<label for="phone">Email:</label>
<input type="email" id="email" name="email" />
</p>
<p>
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" />
</p>
<p>
<label for="occupation">Occupation (Former, if retired):</label>
<input type="text" id="occupation" name="occupation" />
</p>
<div id="shirt">
<p>
<label for="size">Uniform:</label>
<select name="shirt_size" id="shirt_size">
<option value="">Shirt Size</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="XL">XL</option>
<option value="2XL">2XL</option>
<option value="3XL">3XL</option>
</select>
<select name"cap_size" id="cap_size">
<option value="">Cap Size</option>
<option value="XS/S">XS/S</option>
<option value="S/M">S/M</option>
<option value="M/L">M/L</option>
<option value="L/XL">L/XL</option>
</select>
</p>
<p>
<label for="shirtnum">Shirt Number:</label>
<input type="number" id="shirtnum1" name="shirtnum1" placeholder="1st Choice" min="0" max="99" />
<input type="number" id="shirtnum2" name="shirtnum2" placeholder="2nd Choice" min="0" max="99" />
</p>
</div>
<div id="describe">
<p>
<span class="describe1">
<b>Describe any information you deem important regarding your ability and/or availability or any other information you deem important to the season.</b>
<textarea name="description" id="desc" cols="30" rows="10"></textarea>
</span>
</p>
</div>
<div id="ethics">
<h2>Code of Ethics</h2>
<p>
<span class="ethics1">
<input type="checkbox" id="bylaws_rules" name="bylaws_rules" />
I agree to abide by the Bylaws and decisions of the Club and Club Officials.
</span>
</p>
<p>
<span class="ethics1">
<input type="checkbox" id="umpires" name="umpires" />
I agree to accept the decisions of the Umpires and Team Managers.
</span>
</p>
<p>
<span class="ethics1">
<input type="checkbox" id="alcohol" name="alcohol" />
I agree to abstain from alcoholic beverages prior to a game.
</span>
</p>
</div>
<div id="waiver">
<h2>Release of Liability</h2>
<p>
<b>I agree to hold harmless the club.</b>
</p>
<input type="checkbox" id="waiver" name="waiver" />
</div>
<ol class="requires">
<li>Dues are $95 and should be received by April 6, 2016</li>
<li>If you decline to play after being drafted, your registration fee will not be refunded.</li>
<li>All members must be at least 50 years old by December 31, 2016</li>
<li>The deadline for receipt of registrations is April 6, 2016. Registrations received after this date will
not be processed for the player drat. Assignments to teams will then be made according to League guidelines
regarding late registering players.</li>
<li>Registrations received without the correct fee will not be considered as received and will not be valid until the correct fee is received.</li>
</ol>
<p> </p>
<p> </p>
<p> </p>
<p>
<button type="submit" id="register">Register!</button>
</p>
</form>
Thank you for any help!

Posting as a community wiki.
There are a few things wrong here.
First, you never executed the query.
You never check for empty() fields, which might insert empty rows on the table.
Consult the manual:
http://php.net/manual/en/mysqli.query.php
Object oriented style
mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
Procedural style
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
Then you're using the wrong identifier qualifiers for your table:
INSERT INTO 'softball_reg_2016'
^ ^
being regular single quotes, where it should be ticks or no quotes at all:
INSERT INTO `softball_reg_2016`
and that alone would have thrown you a syntax error.
Read up on identifier qualifiers:
http://dev.mysql.com/doc/en/identifier-qualifiers.html
Then you're using desc as a column name which is a MySQL reserved word. That also would have thrown you an error about it. So, either you rename it to something else, or wrap it in ticks.
`desc`
Reference:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Also check for errors:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
Plus, your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Also, since you already declared variables to your POST arrays, why put the POST arrays in the query? Just used the variables. You're using more code for nothing really.
And as noted in comments:
"You also have two input fields with same name: phone. Is that intended or just the copy/paste usual problem? – FirstOne"

You need to execute the query. You have just taken the string.
Here is what you are missing. Put
mysqli_query($conn,$sql);
before the success message.

You didn't excute the query
you have to do
mysqli_query($conn,$query);
before closing the connection

Related

Connect HTML form to SQL database using PHP

//I created an HTML form and created PHP code that should send the contents of the form to my database table, but while the page returns to its original state, which is fine, the data never makes it to the database -- and there is no error.
I originally tried to create a separate PHP form, but after doing some research found this to be more efficient, and cleaner. I just need it to work and to learn if it's possible of not for it to work.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$zipcode = $_POST["zipcode"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$comment = $_POST["comment"];
//connect to server
$dbhost = "localhost";
$username = "root";
$password = "";
$dbname = "point12_guestform";
$mysql = mysqli_connect($dbhost, $username, $password, $dbname);
$query = "INSERT INTO aboutpage
(firstname,lastname,zipcode,email,subject,comment) VALUES
$firstname, $lastname, $zipcode, $email, $subject, $comment";
mysqli_query($mysql, $query);
}
?>
//HTML Form code
<form method="POST" />
<br>
<fieldset>
<div class="col-50">
<input type="text" name="firstname" placeholder="First Name"
required />
</div>
<div class="col-50">
<input type="text" name="lastname" placeholder="Last Name"
required />
</div>
<div class="col-50">
<input type="number" name="zipcode" minlength="5"
maxlength="5" placeholder="Zip Code (where you live)"
required />
</div>
<div class="col-50">
<input type="email" name="email" placeholder="Email"
required />
</div>
<div class="col-50">
<select name="subject" required>
<option selected hidden value="">Please select the option
that best fits your request.
</option>
<option value = "guest">I want to be a guest on the
podcast.
</option>
<option value = "question">I have a question.</option>
<option value = "suggestion">I have a suggestion.</option>
</select>
</div>
<div class="col-50">
<textarea name="comment"
placeholder="Questions/Suggestions/Comments"></textarea>
</div>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</div>
</fieldset>
</form>
//There have been absolutely NO results and NO error messages.//HTML Form code
<form method="POST" />
<br>
<fieldset>
<div class="col-50">
<input type="text" name="firstname" placeholder="First Name"
required />
</div>
<div class="col-50">
<input type="text" name="lastname" placeholder="Last Name"
required />
</div>
<div class="col-50">
<input type="number" name="zipcode" minlength="5"
maxlength="5" placeholder="Zip Code (where you live)"
required />
</div>
<div class="col-50">
<input type="email" name="email" placeholder="Email"
required />
</div>
<div class="col-50">
<select name="subject" required>
<option selected hidden value="">Please select the option
that best fits your request.
</option>
<option value = "guest">I want to be a guest on the
podcast.
</option>
<option value = "question">I have a question.</option>
<option value = "suggestion">I have a suggestion.</option>
</select>
</div>
<div class="col-50">
<textarea name="comment"
placeholder="Questions/Suggestions/Comments"></textarea>
</div>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</div>
</fieldset>
</form>
//There have been absolutely NO results and NO error messages.
Taking all the comments into consideration, the following code would be a good start. I cannot guarantee that this will work out of the box, but it should at least show you some errors/warnings. Once you've corrected those, you can also rest assured that the data going into your DB is not vulnerable to SQL injection. You will still have to escape your output if you choose to display the user entered info.
Please notice:
Error reporting is on (How do I get PHP errors to display?)
MySQL errors will be turned into PHP exceptions (PDO::ERRMODE_EXCEPTION)
Using PDO + parameterized queries (https://phpdelusions.net)
Redirecting to self after query is executed so that a browser refresh doesn't post the data again.
HTML is cleaned up a bit
<?php
// Turn on error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Define your connection properties
$host = 'localhost';
$db = 'point12_guestform';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
// Build up your connection string and set options
// See this for more info: https://phpdelusions.net/pdo#dsn
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// Finally, make a connection using PDO.
// This will throw an exception if something goes awry.
$pdo = new PDO($dsn, $user, $pass, $options);
// Build up your query
// Notice the query is using placeholders `?` instead of directly
// injecting user-entered (dangerous) data.
$sql = 'INSERT INTO aboutpage (firstname,lastname,zipcode,email,subject,comment) VALUES (?,?,?,?,?,?)';
$stmt = $pdo->prepare($sql);
// Finally, execute your query by passing in your data.
// This is known as a parameterized query and prevents SQL injection attacks
$stmt->execute([
$_POST["firstname"],
$_POST["lastname"],
$_POST["zipcode"],
$_POST["email"],
$_POST["subject"],
$_POST["comment"]
]);
// Redirect to self, so that a browser refresh doesn't post data again.
header('Location: '.$_SERVER['PHP_SELF']);
exit;
}
?>
<!-- I clean up some of you HTML too. -->
<form method="post">
<div class="col-50">
<label>
<input type="text" name="firstname" placeholder="First Name" required>
</label>
</div>
<div class="col-50">
<label>
<input type="text" name="lastname" placeholder="Last Name" required>
</label>
</div>
<div class="col-50">
<label>
<input type="number"
name="zipcode"
minlength="5"
maxlength="5"
placeholder="Zip Code (where you live)"
required/>
</label>
</div>
<div class="col-50">
<label>
<input type="email" name="email" placeholder="Email" required>
</label>
</div>
<div class="col-50">
<label>
<select name="subject" required>
<option selected hidden value="">Please select the option
that best fits your request.
</option>
<option value="guest">I want to be a guest on the
podcast.
</option>
<option value="question">I have a question.</option>
<option value="suggestion">I have a suggestion.</option>
</select>
</label>
</div>
<div class="col-50">
<label>
<textarea name="comment" placeholder="Questions/Suggestions/Comments"></textarea>
</label>
</div>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</form>

Mandatory fields in the html form using PHP PDO

I have a html form where i want 3 fields to be mandatory. If the user doesn't fill any one of those fields, then the form shouldn't be submitted and it should tell the user to fill in the mandatory one's. I've used PDO and i dont know how to do it. If someone could help me. Down below i've given both my html and php files.
HTML:
<html>
<head>
<title>Data Insertion</title>
</head>
<body>
<p><span class="Error">* required field.</span></p>
<form method="post" action="su.php">
<h2>Please Fill In Details</h2>
<label for="name">Name </label>
<input type="text" Placeholder="Enter your name" name="name" id="name" />
<span class="Error">*</span>
<br />
<br />
<label for="age">Age </label>
<input type="text" name="age" id="age" placeholder="Enter your age" />
<br />
<br />
<label for="mailid">MailId </label>
<input type="text" name="mailid" id="mailid" placeholder="Enter your Mail Id" />
<span class="Error">*</span>
<br />
<br />
<label for="gender">Gender </label>
<br />
<label for="male">Male </label>
<input type="radio" name="gender" id="gender" value="Male" id="male" />
<label for="female">Female </label>
<input type="radio" name="gender" id="gender" value="Female" id="female" />
<br />
<br />
<label for="qualification">Qualification </label>
<select name="qualification" value="Qualification" id="qualification">
<option value="B.E">SSLC</option>
<option value="P.G">HSC</option>
<option value="SSLC">UG</option>
<option value="HSC">PG</option>
</select>
<br /><br />
<label for="hobbies">Hobbies </label>
<br />
<input type="checkbox" name="hobbies" id="hobbies" value="Cricket" />Cricket
<input type="checkbox" name="hobbies" id="hobbies" value="Music" />Music
<input type="checkbox" name="hobbies" id="hobbies" value="Swimming" />Swimming
<br /><br />
<label for="textarea">Address </label>
<br />
<textarea name="address" id="textarea" rows="15" cols="30"></textarea>
<span class="Error">*</span>
<br /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
PHP:
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
try {
$conn = new PDO("mysql:host=$servername;dbname=testing", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['submit'])){
$name = $_POST['name'];
$age = $_POST['age'];
$mailid = $_POST['mailid'];
$gender = $_POST['qualification'];
$hobbies = $_POST['address'];
if($name !='' || $mailid !='' || $address !=''){
$sql = "Insert into user (Name, Age, MailId, Gender, Qualification, Hobbies, Address)
values ('".$_POST["name"]."', '".$_POST["age"]."', '".$_POST["mailid"]."', '".$_POST["gender"]."', '".$_POST["qualification"]."', '".$_POST["hobbies"]."', '".$_POST["address"]."')";
$conn->exec($sql);
echo "Thank you for registering";
} else {
echo "<p>Insertion failed <br/> Please enter the required fields !";
}}
}
catch(PODException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
Try adding the html 5 attribute "required" on all the required input elements. For example
<input type="text" Placeholder="Enter your name" name="name" id="name" required />
You should also check the POST variables in the php code though, as this doesn't really prevent someone from abusing your service. Ex.
if(!isset($_POST['somevar'])) {
// Do insert
}
In html You should use javascript (e.g. jQuery) to control onsubmit event and validate if mandatory fields are filled with proper values, check this link: jQuery.submit()
In php You should check and validate each var before create and execute query. Simple article about it is here: Sanitize and Validate Data with PHP Filters
This would be good for the start I think ;)
Query string should contain placeholders and then statement should be prepared for execution, check this link:
PDOStatement::bindParam

PHP action insert form not working

I am wondering which one are errors. I've tried to check mysql and nothing inserted into my database.
First of all, my HTML code are like this
<form action="registerAction" method="POST">
<p class="titleRegister"> Login Details </p>
<!-- login details -->
<p> <label for="emailAddress" class="inputField" > Email Address : </label> </p>
<p> <input id="emailAddress" class="registerField" name="ename" required="required" type="text" placeholder="Your email address"/> </p>
<p> <label for="password" class="inputField" > Password : </label> </p>
<p> <input id="password" class="registerField" name="pwd" required="required" type="password" placeholder="Your password"/> </p>
<p> <label for="password" class="inputField" > Confirmation Password : </label> </p>
<p> <input id="password" class="registerField" name="mpwd" required="required" type="password" placeholder="Confirmation password" onBlur="pwdCompare()"/> </p>
<!-- personal details -->
<p class="titleRegister"> Personal Details </p>
<!-- hidden to insert db -->
<input name="registerID" type="hidden"/>
<input name="pic" type="hidden"/>
<p>
<label for="socialTitle" class="inputField" > Title : </label>
<div class="radio">
<input type="radio" name="sTitle" value="mr"> Mr
<input type="radio" name="sTitle" value="mrs"> Mrs
<input type="radio" name="sTitle" value="ms"> Ms
</div>
</p>
<p> <label for="firstName" class="inputField" > First Name : </label> </p>
<p> <input id="firstName" class="registerField" name="fname" required="required" type="text" placeholder="Your first name"/> </p>
<p> <label for="lastName" class="inputField" > Last Name : </label> </p>
<p> <input id="lastName" class="registerField" name="lname" required="required" type="text" placeholder="Your last name"/></p>
<p> <label for="mainAddress" class="inputField" > Main Address : </label> </p>
<p> <input id="mainAddress" class="registerField" name="address" required="required" type="text" placeholder="Your main address"/> </p>
<p> <label for="countryName" class="inputField" > Country : </label> </p>
<?php
include 'dbconnect.php';
echo "<select class=\"selectCSS\" name=\"country\">";
$country = "SELECT DISTINCT * FROM geo_country ORDER BY country";
$showCountry = mysqli_query($mysqli, $country);
while($countryRow = mysqli_fetch_assoc($showCountry))
{
$country = htmlspecialchars ($countryRow['country']);
$countryCode = $countryRow['countryCode'];
echo "<option value=\"$country\">$country</option>\n";
}
echo "</select>";
?>
<p> <label for="cityName" class="inputField" > City : </label> </p>
<?php
include 'dbconnect.php';
echo "<select class=\"selectCSS\" name=\"city\">";
$city = "SELECT DISTINCT * FROM geo_country INNER JOIN geo_city ORDER BY city WHERE geo_country.countryCode = geo_city.countryCode";
$showCities = mysqli_query($mysqli, $city);
while($cityRow = mysqli_fetch_assoc($showCities))
{
$city = htmlspecialchars ($cityRow['city']);
$countryCode = $cityRow['countryCode'];
echo "<option value=\"$city\">$city</option>\n";
}
echo "</select>";
?>
<p> <label for="postalCode" class="inputField" > Postal Code : </label> </p>
<p> <input id="postalCode" class="registerField" name="pcode" required="required" type="text" placeholder="Your postal code"/> </p>
<p> <input class="registerButton" type="submit" value="REGISTER"> </p>
</form>
and my php action come here:
<?php
include 'dbconnect.php';
if ($_POST['pwd']!= $_POST['mpwd']) {
echo("Oops! Password did not match! Try again. ");
}
$register_ID = $_POST['registerID'];
$socialTitle = $_POST['sTitle'];
$firstName = ucfirst(strtoupper($_POST['fname']));
$lastName = ucfirst(strtoupper($_POST['lname']));
$emailAddress = htmlspecialchars($_POST['ename']);
$mainAddress = htmlspecialchars($_POST['address']);
$registerCity = $_POST['city'];
$registerCountry = $_POST['country'];
$postalCode = htmlspecialchars($_POST['pcode']);
$profilePic = $_POST['pic'];
$registerPassword = $_POST['pwd'];
$check = "SELECT * FROM register_user where emailAddress = '$emailAddress'";
$checkTitle = mysqli_query($mysqli,$check);
if (mysqli_num_rows($checkTitle) > 0) {
header("Location: register?error=The name of email has already been taken");
} else {
$insertSQL =
"INSERT INTO register_user ('registerID', 'socialTitle', 'firstName', 'lastName', 'emailAddress', 'mainAddress', 'registerCity', 'registerCountry', 'postalCode', 'profilePic', 'registerPassword')
VALUES ('$register_ID', '$socialTitle', '$firstName', '$lastName', '$emailAddress', '$mainAddress', '$registerCity', '$registerCountry', '$postalCode', '$profilePic', '$registerPassword')";
$queryResult = mysqli_query($mysqli,$insertSQL);
if($queryResult) {
echo "SUCCESS";
echo "<p> Name : $emailAddress </p>";
echo "<p> Detail : $fname </p>";
echo "<p> BACK </p>";
}
}
?>
The results are nothing come out on the new html page and neither in DB. Can you check it out please? Thanks.
You're using the wrong identifiers for your columns, being (single) quotes '.
('registerID', 'socialTitle', 'firstName', 'lastName', 'emailAddress', 'mainAddress', 'registerCity', 'registerCountry', 'postalCode', 'profilePic', 'registerPassword')
change that to:
(registerID, socialTitle, firstName, lastName, emailAddress, mainAddress, registerCity, registerCountry, postalCode, profilePic, registerPassword)
or use backticks.
(`registerID`, `socialTitle`, `firstName`, `lastName`, `emailAddress`, `mainAddress`, `registerCity`, `registerCountry`, `postalCode`, `profilePic`, `registerPassword`)
Using or die(mysqli_error($mysqli)) to mysqli_query() would have shown you the error.
Plus, unless the form action is an index file in a folder called registerAction or a mod rewrite:
it would need to be
<form action="registerAction.php" method="POST">
so, check that. Just an insight.
I would also like to note that your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they are much safer.
Not 100% sure about it, but try changing your html.
This:
<form action="registerAction" method="POST">
To:
<form action="registerAction.php" method="POST">
Assuming registerAction is the name of you php file..

I can't store the data into MySQL

So I have this form. I would like to store the data into my database. However, it's not and there is no error log. I would really appreciate help, as it's due in 2 days and I've been trying for the past week or so.
<form enctype="multipart/form-data" action="preview.php" method="post" class="f">
<p>
<p>
<p><label for="name">Teacher's Name:</label>
<input type="text" style="font-family:Gloria Hallelujah" size="35" name="name" id="name" autofocus required></p>
<p><label for="name">Title:</label>
<input type="text" style="font-family:Gloria Hallelujah" size="35" name="title" id="title" autofocus required></p>
<p><label for="done">Done By:</label>
<input type="text" style="font-family:Gloria Hallelujah" size="35" name="done" id="done" required></p>
<p><label for="no">Class:</label>
<input type="text" style="font-family:Gloria Hallelujah" size="15" name="class" id="no" required></p>
<p><label for="sch">School:</label>
<select name="sch">
<option value="seg">School of Engineering (SEG)</option>
<option value="sit">School of Information Technology (SIT)</option>
<option value="sdn">School of Design (SDN)</option>
<option value="sbm">School of Business Management (SBM)</option>
<option value="shs">School of Health Sciences (SHS)</option>
<option value="scl">School of Chemical & Life Sciences (SCL)</option>
<option value="sidm">School of Interactive and Digital Media (SIDM)</option>
</select>
<p><label for="msg">Show your Gratitude! :</label>
<textarea class="tarea" maxlength="3000" cols="38.5" rows="6" name="comments" placeholder="Enter Message here..." required></textarea>
<p class="limit">Char limit: 3000 chars.</p>
</p>
And it goes to preview.php where it is supposed to store the data.
<?php
include "mysqli.connect.php";
include "fbmain.php";
$sql = "INSERT INTO table(teacherName, title, doneBy, studentClass, school, message)VALUES ('$_POST[name]','$_POST[title]','$_POST[done]','$_POST[class]','$_POST[comments]') where facebookId = '".$me['id']."'";
INSERT command does not need WHERE clause .
P.S : You are wide open to SQL Injection.
('$_POST[name]','$_POST[title]','...
Change to:
('{$_POST[name]}','{$_POST[title]}','...
this is better
see http://ir1.php.net/mysqli_query
And check Database And check WHERE structs
You can Display Errors And Fix them By Put this code After Query
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
$_POST[name] isn't the same as $_POST['name'], $_POST[title] isn't the same as $_POST['title'] etc.
Instead of:
$sql = "INSERT INTO table(teacherName, title, doneBy, studentClass, school, message)VALUES ('$_POST[name]','$_POST[title]','$_POST[done]','$_POST[class]','$_POST[comments]') where facebookId = '".$me['id']."'";
try
$name = $_POST['name'];
$title = $_POST['title'];
$done = $_POST['done'];
$class = $_POST['class'];
$comments = $_POST['comments'];
$sql = "INSERT INTO table(teacherName, title, doneBy, studentClass, school, message)VALUES ('{$name}','{$title}','{$done}','{$class}','{comments}') where facebookId = '".$me['id']."'";
But above is just to get it to work!
It isn't the recommended way of doing this. You should do it with parametized queries... http://forum.codecall.net/topic/44392-php-5-mysqli-prepared-statements/

PHP Form data not inserting into MySQL database

HTML FORM
<form class="form" method="post" action="process.php">
<h4 class="form-heading">Please New Enter Customer Information</h4>
<label for="inital">Inital:</label>
<select id="inital" name="inital" required="required">
<option value="mr">Mr</option>
<option value="ms">Ms</option>
<option value="mrs">Mrs</option>
<option value="prof">Prof</option>
<option value="dr">Dr</option>
</select>
<label for="firstname">First Name:</label>
<input type="text" placeholder="First Name" name="firstname" required="required" >
<label for="lastname">last Name:</label>
<input type="text" placeholder="Last Name" name="lastname" required="required">
<label for="mobile">Mobile:</label>
<input type="tel" placeholder="Mobile" name="mobile" required="required">
<label for="landline">Landline:</label>
<input type="tel" placeholder="Landline" name="landline">
<label for="email">Email:</label>
<input type="email" placeholder="Email" name="email" required="required">
<label for="address">Address:</label>
<input type="text" placeholder="Address" name="address" required="required">
<label for="postocde">Postal Code:</label>
<input type="text" placeholder="Post Code" name="postcode">
<label for="accessibility">Accessibility:</label>
<input type="text" placeholder="Accessibility Needs" name="accessibility" value="">
<button class="btn btn-large btn-primary" type="submit">Enter</button>
process.php
<? php
require( '../connect_db.php' ) ;
$inital = $sql->real_escape_string($_POST[inital]);
$firstname = $sql->real_escape_string($_POST[firstname]);
$lastname = $sql->real_escape_string($_POST[lastname]);
$mobile = $sql->real_escape_string($_POST[mobile]);
$landline = $sql->real_escape_string($_POST[landline]);
$email = $sql->real_escape_string($_POST[email]);
$address = $sql->real_escape_string($_POST[address]);
$postcode = $sql->real_escape_string($_POST[postcode]);
$accessibility = $sql->real_escape_string($_POST[accessibility]);
$query = "INSERT INTO `customer` (inital, firstname, lastname, mobile, landline, email, address, postcode, accessibility) VALUES ('$inital','$firstname', '$lastname','$mobile','$landline','$email','$address','$postcode','$accessibility')";
/* execute the query, nice and simple */
$sql->query($query) or die($query.'<br />'.$sql->error);
?>
I have tried alternatives too but to no satisfaction like not including $inital =($_POST[inital]); Instead putting right into INSERT INTO section but that still does not help either.
It either prints out the whole code on screen or blank. I've looked at similar problems on here and on forums all them seem to present the issue differently and when i change it suit the so called answer it still does not work!
My other page that lists all the tables using the following connection required statment works works fine so there is no problem with connection to the database but at this moment just cannot insert content. Grr
Two problems:
change <? php to <?php
and then add quotes to your post data values. $_POST[inital] to $_POST['inital']
and for your information i would do isset($_POST['value']) ? $_POST['value'] : '';
you still need to check post value before using it.
Check the <? php tag. it should be <?php

Categories