How to write information from html form to MySQL Database - php

Alright, so I'm setting up a website that has a form on it and I want to save all the information that the user types into the form to my MySQL Database. The form is coded like this:
<form method="post" action="claim.php" name="ClaimForm" id="ClaimForm" autocomplete="on">
<fieldset>
<legend>Contact Details</legend>
<div>
<label for="firstname" accesskey="U">Your First Name</label>
<input name="firstname" type="text" id="firstname" placeholder="Enter your name" required />
</div>
<div>
<label for="lastname" accesskey="U">Your Last Name</label>
<input name="lastname" type="text" id="lastname" placeholder="Enter your name" required />
</div>
<div>
<label for="email" accesskey="E">Email</label>
<input name="email" type="email" id="email" placeholder="Enter your Email Address" pattern="^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$" required />
</div>
<div>
<label for="streetaddress">Street Address</label>
<input name="streetaddress" type="text" id="streetaddress" placeholder="123 Stanley dr." required />
</div>
<div>
<label for="postalcode">Postal Code</label>
<input name="postalcode" type="text" id="postalcode" placeholder="12345, A1B 2C3, etc." required />
</div>
<label for="city">City</label>
<input name="city" type="text" id="city" placeholder="Schenectady" required />
<div>
<label for="state">State/Province</label>
<input name="state" type="text" id="state" placeholder="New York" required />
</div>
<div>
<label for="country">Country</label>
<input name="country" type="text" id="country" placeholder="United States" required />
</div>
</fieldset>
<fieldset>
<legend>Extra</legend>
<div>
<label for="controllers" accesskey="S">Number of Controllers</label>
<select name="controllers" id="controllers" required="required">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div>
<label for="color" accesskey="C">Color</label>
<select name="color" id="color" required="required">
<option value="Black">Black</option>
<option value="White">White</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Gold">Gold</option>
<option value="Purple">Purple</option>
</select>
</div>
</fieldset>
<fieldset>
<legend>Captcha Verification</legend>
<label for="verify" accesskey="V" class="verify"><img src="captcha.php" alt="Verification code" /></label>
<input name="verify" type="text" id="verify" size="6" required style="width: 50px;" title="This confirms you are a human user and not a spam-bot." />
</fieldset>
<input type="submit" class="submit" id="submit" value="Submit" />
</form>
I tried using this code in Claim.php to try and save that to the database:
<?php
$mysql_host = "localhost";
$mysql_username = "username";
$mysql_password = "password";
$mysql_database = "database";
mysql_select_db($mysql_database, mysql_connect($mysql_host, $mysql_username, $mysql_password));
//Sending form data to sql db.
mysqli_query("INSERT INTO Information (Firstname,Lastname,Email,StreetAddress,PostalCode,City,StateProvince,Country,Controllers,Color) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[email]','$_POST[streetaddress]','$_POST[postalcode]','$_POST[city]','$_POST[state]','$_POST[country]','$_POST[conrollers]','$_POST[color]'))");
?>
Is there anything wrong with my code? Or is my database structured wrong? I just started learning how to code and this is confusing me.
Picture of my database structure:

Please use mysqli. I have altered your code to prepare the insert instead.
If you didn't, it would be a huge SQL injection party.
Also, to access $_POST, you should give a string index, like $_POST['firstname']. Though it works like $_POST[firstname], PHP will emit a warning.
<?php
$mysql_host = "localhost";
$mysql_username = "username";
$mysql_password = "password";
$mysql_database = "database";
$mysqli = new Mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
$prepare = $mysqli->prepare("INSERT INTO `Information`(`Firstname`,`Lastname`,`Email`,`StreetAddress`,`PostalCode`,`City`,`StateProvince`,`Country`,`Controllers`,`Color`) VALUES (?,?,?,?,?,?,?,?,?,?)");
$prepare->bind_param("ssssssssss", $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['streetaddress'], $_POST['postalcode'], $_POST['city'], $_POST['state'], $_POST['country'], $_POST['controllers'], $_POST['color']);
$prepare->execute();
$mysqli->close();
?>

You may want to consider getting your php info to see what version you are running.
If you are running a version that supports mysqli objects you may want to start there and instantiate an object of mysqli.
Mysqli documentation: http://us.php.net/manual/en/book.mysqli.php
This makes it so your methods are not deprecated.
Also keep in mind you are not going to see any errors in your output when posting to your page. This can complicate debugging. Use these two lines of php to see errors:
error_reporting(E_ALL);
ini_set('display_errors', '1');
It is also good practice to make sure you set all of your variables. You can do this by using the isset() method to check they are set before you insert your data.
I bet you will find some things wrong when errors are set.
It looks like you are not accessing your variables correctly.
$_POST[varname] will not access the data and throw an error message.
$_POST['varname'] will work.

The first thing I see is that you didn't escape your values before inserting them in your query.
Imagine I write this in your email field :
'); drop table Information --
And you lost all your data.
To escape values, you could use the mysql_real_escape_string function() like this :
"......".mysql_real_escape_string($_POST['email'])."...."

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>

Can't insert values in database using form

I have a form where users can register other accounts. It was working fine until I changed the data type of the column date to data type date (I was using varchar so I changed it to date). After changing the datatype, the registration stopped working. I don't get an error but I can't see the new account when I try to view the records.
Here's my form:
<div class="main">
<div class="one">
<div class="register">
<center><h3>Add Account</h3></center>
<form name="reg" action="code_exec.php" onsubmit="return validateForm()" method="post">
<div>
<label>ID</label>
<input type="text" name="id" required>
</div>
<div>
<label>First Name</label>
<input type="text" name="firstname" required>
</div>
<div>
<label>Last Name</label>
<input type="text" name="lastname" required>
</div>
<div>
<label>Email</label>
<input type="text" name="email" placeholder="user#teamspan.com" required>
</div>
<div>
<label>Username</label>
<input type="text" name="username" required>
</div>
<div>
<label>Password</label>
<input type="password" name="password" required>
</div>
<div>
<label>Street Address</label>
<input type="text" name="street" required>
</div>
<div>
<label>Town/Suburb</label>
<input type="text" name="town" required>
</div>
<div>
<label>City</label>
<input type="text" name="city" required>
</div>
<div>
<label>Contact</label>
<input type="text" name="contact" required>
</div>
<div>
<label>Gender</label>
<select name="gender" required>
<option disabled selected hidden>Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div>
<label>User Levels</label>
<select name="user_levels" required>
<option disabled selected hidden>Select Access Level</option>
<option value="0">Employee</option>
<option value="1">Administrator</option>
<option value="2">Manager</option>
<option value="1">HR</option>
</select>
</div>
<div>
<label>Date</label>
<input type="text" readonly="readonly" name="date" value="<?php echo date("m/j/Y");?>" required>
</div>
<div>
<label>Sick Leave</label>
<input type="text" name="sickleave" required>
</div>
<div>
<label>Vacation Leave</label>
<input type="text" name="vacationleave" required>
</div>
<div>
<label>Picture (Link)</label>
<input type="text" name="picture" value="img/emp/" required>
</div>
<div>
<label></label>
<input type="submit" name="submit" value="Add Account" class="button" style="color: white;" />
<a href="hr_panel.php"><input type="button" value="Back" class="button" style="color: white;" />
</div>
</form>
</div>
</div>
And here's code_exec.php
<?php
session_start();
include('connection.php');
$id=$_POST['id'];
$username=$_POST['username'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$street=$_POST['street'];
$town=$_POST['town'];
$city=$_POST['city'];
$contact=$_POST['contact'];
$gender=$_POST['gender'];
$password=$_POST['password'];
$user_levels=$_POST['user_levels'];
$date=$_POST['date'];
$picture=$_POST['picture'];
$sickleave=$_POST['sickleave'];
$vacationleave=$_POST['vacationleave'];
mysqli_query($bd, "INSERT INTO employee(id, firstname, lastname, username, email, street, town, city, contact, gender, password, user_levels, date, picture, sickleave, vacationleave)
VALUES ('$id', '$firstname', '$lastname', '$username', '$email', '$street', '$town', '$city', '$contact', '$gender', '$password', '$user_levels', '$date', '$picture', '$sickleave', '$vacationleave')");
echo "<script>alert('Successfully Added!'); window.location='register.php'</script>";
mysqli_close($con);
?>
Database Schema:
DB Schema
As others have already stated, your date format may not be correct. And you need to look at securing your queries against sql injection.
In order to get you date issue fixed try replacing:
$date=$_POST['date'];
With:
$date=date('Y-m-d', strtotime($_POST['date']));
The Date format for sql is described as YYYY-MM-DD meaning a four digit year-two digit month - two digit day.
You need to convert the received date from your input date :
$dt = \DateTime::createFromFormat('m/j/Y', $_POST['date']);
See this StackOverflow answer for more informations.
Moreover, as #Syscall said, you should also pay attention to your query which is open to SQL injections. To prevent that, you should use a PDO statement, for example :
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
Example taken from How can I prevent SQL injection in PHP?

Send html form data to sql database via 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

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