bellow you see my form validation script that I have been working on for a while. The script is suppose to check if the "Name:" is first not empty and then if it only contains letters and then insert the data. Likewise for the "Price:" it is suppose to check if it is not empty and then it's only digits. So far I have failed to make all the functions working and here are the problems as it sits right now:
in general it does not insert data to the table
regardless says price is required (even if the price is given)
when there is given numbers in the name field, there is no error
and here is the script:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$con=mysqli_connect("localhost","xxxxx","xxxxx","my_project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// define variables and set to empty values
$nameErr = $priceErr = $catErr = $condErr = $regionErr = "";
$product_name = $product_price = $product_cat = $product_cond = $product_region = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["product_name"]))
{
$nameErr = "Name is required";
}
else if (!preg_match("/^[a-zA-Z ]*$/",$product_name))
{
$nameErr = "Only letters and white space allowed";
}
if (empty ($_POST ["product_price"]))
{
$priceErr = "Price is required";
}
else if(!ctype_digit($product_price))
{
$priceErr = "Price is required";
}
else
{
$product_name = test_input($_POST["product_name"]);
$product_price = test_input($_POST["product_price"]);
$sql= "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con,$sql))
{
echo 'Error: ' . mysqli_error($con);
}
else
{
echo "1 record added";
}
mysqli_close($con);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="product_name" value="<?php echo $product_name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
price: <input type="text" name="product_price" value="<?php echo $product_price;?>">
<span class="error">* <?php echo $priceErr;?></span>
<br><br>
Condition:
<select name="product_cond" required >
<option value="" >SELECT</option>
<option value="Used" >Used </option>
<option value="new" >New</option>
</select>
Category:
<select name="product_cat" required >
<option value="" >SELECT</option>
<option value="books" >books</option>
<option value="Computers" >Computers</option>
<option value="Hardware/Tools" >Hardware/Tools </option>
<option value="Cars" >Cars</option>
<option value="home Appliances" >home Appliances</option>
</select>
Region:
<select name="product_region" required >
<option value="" >SELECT</option>
<option value="Oulu" >Oulu</option>
<option value="Turku" >Turku</option>
<option value="Helsinki" >Helsinki </option>
<option value="Tornio" >Vaasa</option>
<option value="Tampere" >Tampere</option>
<option value="Kemi" >Kemi</option>
<input type="submit">
</form>
</body>
and here is the example that I have used and modified:
http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_special
I'd suggest to use an array of errors instead of variables.
Then you should access the variables you send by the form like $_POST['variable']
Try this code:
$errors = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["product_name"])) {
$errors['name'] = "Name is required";
} else if (!preg_match("/^[a-zA-Z ]*$/", $_POST['product_name'])) {
$errors['name'] = "Only letters and white space allowed";
}
if (empty($_POST ["product_price"])) {
$errors['price'] = "Price is required";
} else if (!ctype_digit($_POST['product_price'])) {
$errors['price'] = "Price is required";
}
if(count($errors) == 0){
$product_name = test_input($_POST["product_name"]);
$product_price = test_input($_POST["product_price"]);
$sql = "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con, $sql)) {
echo 'Error: ' . mysqli_error($con);
} else {
echo "1 record added";
}
}
}
Related
this is the undefined error that i got
the update is working. but after i clicked the submit button, the selected dropdown gave me this error.
$row=array();
if (isset($_GET['typeid'])) {
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
}
// update record
if(isset($_POST['submit'])){
$id = mysqli_real_escape_string($link,$_POST['idtype']);
$type = mysqli_real_escape_string($link, $_POST['type']);
$status = mysqli_real_escape_string($link, $_POST['status']);
$update = mysqli_real_escape_string($link, $_SESSION['idinfostaf']);
$result = mysqli_query($link, "UPDATE vehicletype SET vehicle_Type='$type', status_vehicleType='$status', updateby_vehicleType='$update' WHERE id_vehicleType=".$id);
if ($result) {
$success = "Record updated successfully!";
}
else {
$error = "Error updating record...";
}
}
i put the php code and html on the same page..below is the html
<div class="form-group">
<label>Choose Vehicle Type Status</label>
<select class="form-control" name="status" required class="form-control" value="<?php if(isset($row['status_vehicleType'])){ echo $row['status_vehicleType'];} ?>">
<option value="">Select Vehicle Type</option>
<option
value="1" <?php if ($row['status_vehicleType']==$_GET["typeid"]) { echo 'selected="selected"' ;} ?> >Enabled</option>
<option
value="0" <?php if ($row['status_vehicleType']== $_GET["typeid"]) { echo 'selected="selected"' ;} ?> >Disabled</option>
</select>
<hr>
<button type="submit" name="submit" class="btn btn-info">Submit </button>
<span class="text-success"><?php if (isset($success)) { echo $success; } ?></span>
<span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
i used the typeid to carry the values.
Try this:
<select value="<?php if(isset($row['status_vehicleType'])){ echo $row['status_vehicleType'];} ?>">
<option value="">Select Vehicle Type</option>
<option value="1" <?php
if(isset($row['status_vehicleBrand'])) {
if ($row['status_vehicleBrand']==$_GET["typeid"]) {
echo 'Selected' ;
}
} ?> >Enabled</option>
<option value="0" <?php
if(isset($row['status_vehicleBrand'])) {
if ($row['status_vehicleBrand']==$_GET["typeid"]) {
echo 'Selected' ;
}
} ?> >Disabled</option>
</select>
Looking for help please. I'm new to php and my course needs me to save form data to an sql database. I have the below code which creates my error message "Something went wrong". I'm studying online and my lecturer is less than useless at helping. Can anyone tell me where I am going wrong please?
My database reads and writes ok elsewhere..
<?php
$page_title = "Login Page";
session_start();
include('header.php');
require_once("validation_functions.php");
require_once('functions.php');
require_once('connection.php');
// Check if form was submitted
if (isset($_POST['submit'])) {
// Remove whitespace from beginning and end of values
$title = trim($_POST["Title"]);
$director = trim($_POST["Director"]);
$producer = trim($_POST["Producer"]);
$running_time = trim($_POST["Running"]);
$starring = trim($_POST["Starring"]);
$distributor = trim($_POST["Distributor"]);
// Escape strings and filter input to prevent SQL injection
$title = mysqli_real_escape_string($connection, $title);
$director = mysqli_real_escape_string($connection, $director);
$producer = mysqli_real_escape_string($connection, $producer);
$starring = mysqli_real_escape_string($connection, $starring);
$distributor = mysqli_real_escape_string($connection, $distributor);
$running_time = intval($running_time);
if (isset($_POST["Rel"])) { $release = $_POST["Rel"]; }
if (isset($_POST["Genre"])) { $genre = $_POST["Genre"]; }
if (isset($_POST["Rating"])) { $rating = $_POST["Rating"]; }
$form_errors = false;
// Check if fields are blank
if (is_blank($title) || is_blank($director) || is_blank($producer) || is_blank($release) || is_blank($running_time) || is_blank($starring) || is_blank($distributor)) {
$blank_message = "<p class='error-msg'>All fields are required.</p>";
$form_errors = true;
}
// Check if running time is a valid number
if (isset($running_time) && !filter_var($running_time, FILTER_VALIDATE_INT)) {
$number_message = "<p class='error-msg'>Running time is not a valid number.</p>";
$form_errors = true;
}
// Check if movie already exists
if (record_exists("SELECT * FROM Movie WHERE Movie.Title = '{$title}'")) {
$exists_message = "<p class='error-msg'>This movie already exists in the database.</p>";
$form_errors = true;
}
if ($form_errors == false) {
$insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel, Running, GenreID, Starring, Distributor, Rating) VALUES ('{$title}', '{$director}', '{$producer}', '{$release}', '{$running_time}'', '{$genre}', '{$starring}', '{$distributor}', '{$rating}')";
if (mysqli_query($connection, $insert_movie)) {
$movie_id = mysqli_insert_id($connection);
$success_message = "<p class='success-msg'>The movie has been successfully added to the database.</p>";
}
else {
$error_message = "<p class='error-msg'>Something went wrong. Please try again.</p>";
}
}
}
//php code ends here
?>
<!-- // PUT ERRORS HERE-->
<?php if (isset($blank_message)) { echo $blank_message; } ?>
<?php if (isset($number_message)) { echo $number_message; } ?>
<?php if (isset($date_message)) { echo $date_message; } ?>
<?php if (isset($exists_message)) { echo $exists_message; } ?>
<?php if (isset($success_message)) { echo $success_message; } ?>
<?php if (isset($error_message)) { echo $error_message; } ?>
<form action="<?php htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" enctype="multipart/form-data" id="movieinput">
Title:<br>
<input type="text" name="Title" placeholder="e.g. Aliens" data-validation="required" value="<?php if (isset($title)) { echo $title; } ?>"><br>
Director:<br>
<input type="text" name="Director" placeholder="e.g. Ridley Scott" data-validation="required" value="<?php if (isset($director)) { echo $director; } ?>"><br>
Producer:<br>
<input type="text" name="Producer" placeholder="e.g. Gale Ann Hurd" data-validation="required" value="<?php if (isset($producer)) { echo $producer; } ?>"><br>
Release Date:<br>
<input type="date" name="Rel" format="yyyy/mm/dd" value="<?php if (isset($date)) { echo $date; } ?>"><br>
Running Time (mins):<br>
<input type="number" pattern=".{1,3}" name="Running" placeholder="e.g. 137" data-validation="required" value="<?php if (isset($running)) { echo $running; } ?>"><br>
Genre:<br><select name="Genre" value="<?php if (isset($genre)) { echo $genre; } ?>"><br>>
<option value="drama" name="drama">Drama</option>
<option value="documentary" name ="documentary">Documentary</option>
<option value="scifi" name="scifi" selected>Sci-Fi</option>
<option value="comedy" name="comedy">Comedy</option>
<option value="biopic" name ="biopic">Biopic</option>
<option value="horror" name="horror">Horror</option>
</select><br>
Starring:<br>
<input type="text" name="Starring" placeholder="e.g. Sigourney Weaver, Michael Biehn, William Hope" value="<?php if (isset($starring)) { echo $starring; } ?>"><br>
Distributor:<br>
<input type="text" name="Distributor" placeholder="e.g. 20th Century Fox" data-validation="required" value="<?php if (isset($distributor)) { echo $distributor; } ?>"><br>
Rating:<br><select name="Rating" value="<?php if (isset($rating)) { echo $rating; } ?>"><br>>>
<option
value="one">1
</option>
<option
value="two">2
</option>
<option
value="three">3
</option>
<option
value="four">4
</option>
<option
value="five">5
</option>
</select><br>
<br>
<input type="submit" name="submit" value="Submit"/>
</form>
<script> </script>
You are using SQL database from php and using mysqli_query() function to insert which would definitely not work. You have to use PDO. to access SQL database.
Connect to SQL Server through PDO using SQL Server Driver
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=0ahUKEwjk4MS-w-HRAhUPR48KHbLaAIMQFggdMAE&url=http%3A%2F%2Fphp.net%2Fmanual%2Fen%2Fref.pdo-dblib.php&usg=AFQjCNGG9EMmNv41NHQfjhpapjqhugBYQA
> $insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel,
> Running, GenreID, Starring, Distributor, Rating) VALUES ('{$title}',
> '{$director}', '{$producer}', '{$release}', '{$running_time}'',
> '{$genre}', '{$starring}', '{$distributor}', '{$rating}')";
use this instead of
> $insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel,
> Running, GenreID, Starring, Distributor, Rating) VALUES ('$title',
> '$director', '$producer', '$release', '$running_time', '$genre',
> '$starring', '$distributor', '$rating')";
In this case, some of the below possibility will cause this issue.
Input type is mismatch with column data type in database table.
Required parameter to be used to insert into the table.
One suggestion to ensure that there is no issue in INSERT query. Just print the insert statement in browser and execute that manually in DB.
$insert_movie = "INSERT INTO Movie (Title, Director, Producer, Rel, Running, GenreID, Starring, Distributor, Rating) VALUES ('{$title}', '{$director}', '{$producer}', '{$release}', '{$running_time}'', '{$genre}', '{$starring}', '{$distributor}', '{$rating}')";
echo $insert_movie; exit;
Try this and will continue the debugging if there is no issue in insert statement.
Cheers!
This php file is using server side validation via post method as the user enters data into the input devices. The only problem I'm having is inserting the data into the customers table as it doesn't work. I know this because i have created test php file that displays all the customer tables content and the data the user enters is not there. Where have i gone wrong?
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Prac 2 Task 12</title>
</head>
<body>
<?php
$conn = mysql_connect("localhost", "twa291", "......");
mysql_select_db("factory291", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "SELECT * FROM customer";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
$ename = $elname = $ecus = $epcode = "";
$fnamecus = $lnamecus = $idcus = $pcde = "";
$error_report = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["customerid"])) {
$ecus = "Customer ID is required";
$error_report = true;
} else {
$idcus = input_t($_POST["customerid"]);
// check if numeric
if (preg_match("/[^0-9]/",$idcus)) {
$ecus = "Only numbers allowed";
$error_report = true;
}
if(strlen($idcus) != 6 && ($idcus) != null)
{
$ecus = "Customer ID must be 6 digits";
$error_report = true;
}
}
if (empty($_POST["customerfname"])) {
$ename = "First name is required";
$error_report = true;
} else {
$fnamecus= input_t($_POST["customerfname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-]*$/",$fnamecus)) {
$ename = "Only alphabetic letters and hyphen";
$error_report = true;
}
if(strlen($fnamecus) > 20 && ($fnamecus) != null)
{
$ename = "First name can't be more that 20 characters long";
$error_report = true;
}
}
if (empty($_POST["customerlname"])) {
$elname = "Last name is required";
$error_report = true;
} else {
$lnamecus = input_t($_POST["customerlname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-]*$/",$lnamecus)) {
$elname = "Only alphabetic letters and hyphen";
$error_report = true;
}
if(strlen($lnamecus) > 20 && ($lnamecus) != null)
{
$elname = "Last name can't be more that 20 characters long";
$error_report = true;
}
}
if (!is_null($_POST["postcode"])) {
$pcde = input_t($_POST["postcode"]);
// check if name only contains letters and whitespace
if (preg_match("/[^0-9]/",$pcde)) {
$epcode = "Only numbers allowed";
$error_report = true;
}
if(strlen($pcde) != 4 && ($pcde) != null)
{
$epcode = "Post code must be 4 digits";
$error_report = true;
}
}
}
if($error_report != true) {
$query="INSERT INTO customer (customerID, firstName, lastName, Address, suburb, state, postcode)
VALUES ('customerid', 'customerfname', ‘customerlname', 'customeraddress', 'suburb',
'state', 'postcode')";
$queryResult = mysql_query($query, $conn)
or die ('Problem with query' . mysql_error());
echo "correct";
}
function input_t($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h1>Customer Information Collection <br /></h1>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="custinfo" >
<table>
<tr>
<td><label for="customerid">Customer ID (integer value): </label></td>
<td><input type="text" id="customerid" name="customerid" size=11 value="<?php
echo $idcus;?>"/><span class="error">* <?php echo $ecus;?></span></td>
</tr>
<tr>
<td><label for="customerfname">Customer Frist Name: </label></td>
<td><input type="text" id="customerfname" name="customerfname" size=50 value="<?php
echo $fnamecus;?>"/><span class="error">* <?php echo $ename;?></span></td>
</tr>
<tr>
<td><label for="customerlname">Customer Last Name: </label></td>
<td><input type="text" id="customerlname" name="customerlname" size=50 value="<?php
echo $lnamecus;?>"/><span class="error">* <?php echo $elname;?></span></td>
</tr>
<tr>
<td><label for="customeraddress">Customer Address: </label></td>
<td><input type="text" id="customeraddress" name="customeraddress" size=65/></td>
<td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td>
State:<select name="state" id="state">
<option value="select">--</option>
<option value="ACT">ACT</option>
<option value="NSW">NSW</option>
<option value="NT">NT</option>
<option value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="WA">WA</option>
</select>
</td>
<td><label for="postcode"> Post Code: </label><input type="text" id="postcode"
name="postcode" size=4 value="<?php
echo $pcde;?>"/><span class="error"><?php echo $epcode;?></span></td>
</tr>
</table>
<p><input type="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</tr>
</form>
</body>
</html>
You need to call mysql_query on your $query -- right now you're just defining the $query object and then ignoring it for the rest of the page.
Add something like the following on the line before echo "correct";
$queryResult = mysql_query($query, $conn)
or die ('Problem with query' . mysql_error());
n.b. I'll echo #Ozmah's comment about looking into PDO or mysqli functions - learning the deprecated plain mysql functions will be of dubious value.
Below is my script that inserts data into a table. My question is only concerning form validations in php.
Here is my php code:
<?php
//Here I have defined an error variable for each of the variables in the project
$nameErr = $productErr = $priceErr = $catErr = $regionErr = "";
$product_name = $product_cond = $product_price = $product_cat = $product_region = "";
$con=mysqli_connect("localhost","*****","*****","my_project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// here in this elseif, I check the number of characters in the field and then it is suppose to send an error (on the same page) if it does not match
elseif (strlen($_POST['product_name']) < 5 ) {
$productErr = "name is too short";
}
elseif (strlen($_POST['product_name']) > 10) {
$productErr = "name is too long";
}
elseif (empty($_POST['product_cond'])) {
$productErr = "product condition required";
}
else
{
$sql= "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con,$sql))
{
echo 'Error: ' . mysqli_error($con);
}
else
{
echo "1 record added";
}
}
mysqli_close($con);
?>
and here is my html page:
<html>
<body>
<h3> Please enter your product information bellow: </h3>
<form action="insert_data.php" method="post">
Product name: <input type="text" name="product_name" >
// here I added this line that is suppose to do echo the error message:
<span class="error">* <?php echo $nameErr;?></span>
Condition:
<select name="product_cond">
<option value="" >SELECT</option>
<option value="Used" >Used </option>
<option value="new" >New</option>
</select>
Category:
<select name="product_cat">
<option value="" >SELECT</option>
<option value="books" >books</option>
<option value="Computers" >Computers</option>
<option value="Hardware/Tools" >Hardware/Tools </option>
<option value="Cars" >Cars</option>
<option value="home Appliances" >home Appliances</option>
</select>
Region:
<select name="product_region">
<option value="Oulu" >Oulu</option>
<option value="Turku" >Turku</option>
<option value="Helsinki" >Helsinki </option>
<option value="Tornio" >Tornio</option>
<option value="Tampere" >Tampere</option>
<option value="Kemi" >Kemi</option>
</select>
Product price: <input type="text" name="product_price">
<input type="submit">
</form>
</body>
</html>
The problem is that this method still prevents the data to be inserted into the table but it does not give me an error instead, it just gives me a blank screen. What is the problem.
(I'm using this example provided by w3school: http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_required)
Try below code in php:
<?php
$con=mysqli_connect("localhost","*****","*****","my_project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$error = false;
$errorMsg = "";
if (strlen($_POST['product_name']) < 5 ) {
$error = true;
$errorMsg. = "name is too short";
}
elseif (strlen($_POST['product_name']) > 10) {
$error = true;
$errorMsg. = "name is too long";
}
if (empty($_POST['product_cond'])) {
$error = true;
$errorMsg. = "product condition required<br/>";
}
if (empty($_POST['product_price'])) {
$error = true;
$errorMsg. = "product price required<br/>";
}
if (empty($_POST['product_cat'])) {
$error = true;
$errorMsg. = "product category required<br/>";
}
if (empty($_POST['product_region'])) {
$error = true;
$errorMsg. = "product region required<br/>";
}
if (empty($_POST['email'])) {
$error = true;
$errorMsg. = "email required<br/>";
}
if (empty($_POST['phone_num'])) {
$error = true;
$errorMsg. = "phone required<br/>";
}
if(!$error)
{
$sql= "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES ('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con,$sql))
{
echo 'Error: ' . mysqli_error($con);
}
else
{
echo "1 record added";
}
}else{
echo $errorMsg;
}
mysqli_close($con);
?>
PHP CODE
<?php
//Here I have defined an error variable for each of the variables in the project
if (isset($_POST['product_name']) && isset($_POST['product_cond']) && isset($_POST['product_price']) && isset($_POST['product_cat']) && isset($_POST['product_region']) && isset($_POST['Email']) && isset($_POST['PhoneNumber'])) {
$nameErr = $productErr = $priceErr = $catErr = $regionErr = "";
$product_name = $product_cond = $product_price = $product_cat =
$product_region = "";
$con = mysqli_connect("localhost", "*****", "*****", "my_project");
if
(mysqli_connect_errno()
) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// here in this elseif, I check the number of characters in the
field and then it is suppose to send an error(on the same page) if it
does not match
elseif (strlen($_POST['product_name']) < 5) {
$productErr = "name is too short";
} elseif (strlen($_POST['product_name']) > 10) {
$productErr = "name is too long";
} elseif (empty($_POST['product_cond'])) {
$productErr = "product condition required";
}
else {
$sql = "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST['product_name']','$_POST['product_cond']','$_POST['product_price']','$_POST['product_cat']','$_POST['product_region']','$_POST['Email']','$_POST['PhoneNumber']')";
if (!mysqli_query($con, $sql)) {
echo 'Error: ' . mysqli_error($con);
} else {
echo "1 record added";
} } mysqli_close($con);
}
?>
HTML
<html>
<body>
<h3> Please enter your product information bellow: </h3>
<form action="insert_data.php" method="post">
Product name: <input type="text" name="product_name" pattern="[a-zA-Z]{4,9}" required>
// here I added this line that is suppose to do echo the error message:
<span class="error">* <?php echo $nameErr;?></span>
Condition:
<select name="product_cond" required>
<option value="" >SELECT</option>
<option value="Used" >Used </option>
<option value="new" >New</option>
</select>
Category:
<select name="product_cat" required>
<option value="" >SELECT</option>
<option value="books" >books</option>
<option value="Computers" >Computers</option>
<option value="Hardware/Tools" >Hardware/Tools </option>
<option value="Cars" >Cars</option>
<option value="home Appliances" >home Appliances</option>
</select>
Region:
<select name="product_region" required>
<option value="Oulu" >Oulu</option>
<option value="Turku" >Turku</option>
<option value="Helsinki" >Helsinki </option>
<option value="Tornio" >Tornio</option>
<option value="Tampere" >Tampere</option>
<option value="Kemi" >Kemi</option>
</select>
Product price: <input type="text" name="product_price" pattern="[0-9]{0,5}" required>
<input type="submit">
</form>
SECOND EDIT
It seems that upon loading the page, not when submitting, that the two entries (blank rows) are added to my database. I'm really struggling to find my problem here but I have a feeling it's a fairly stupid error.
I'm having an issue with my php/mysql code posting extra blank rows along with what it's supposed to post. The code for the validation of the data from my form an for the transmission of the info to the database is below. Every time I enter data in my form and submit it it works fine, however it adds extra rows to the tblLocation, the tblWhere works fine. Can anyone lead me in the right direction here? Let me know if you need more of my code.
CODE IS AS FOLLOWS
if (isset($_POST['butSubmit'])) {
// set variables to data from form
$user= mysql_real_escape_string($_POST["txtUser"]);
$fName= mysql_real_escape_string($_POST["txtFname"]);
$lName= mysql_real_escape_string($_POST["txtLname"]);
$email= mysql_real_escape_string($_POST["txtEmail"]);
$date= date(DATE_RFC822);
$street= mysql_real_escape_string($_POST["txtStreet"]);
$city= mysql_real_escape_string($_POST["txtCity"]);
$state= mysql_real_escape_string($_POST["lstStates"]);
$zip= mysql_real_escape_string($_POST["txtZip"]);
//handle html characters
$user = htmlentities($user, ENT_QUOTES);
$fName = htmlentities($fName, ENT_QUOTES);
$lName = htmlentities($lName, ENT_QUOTES);
$email = htmlentities($email, ENT_QUOTES);
$date = htmlentities($date, ENT_QUOTES);
$street = htmlentities($street, ENT_QUOTES);
$city = htmlentities($city, ENT_QUOTES);
$state = htmlentities($state, ENT_QUOTES);
$zip = htmlentities($zip, ENT_QUOTES);
$errorMsg=array();
// initiate testing procedures for form contents
if($user==""){
$errorMsg[]="Please enter your Username";
} else {
$valid = verifyAlphaNum ($user); /* test for non-valid data */
if (!$valid){
$error_msg[]="Username must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($fName==""){
$errorMsg[]="Please enter your First Name";
} else {
$valid = verifyAlphaNum ($fName); /* test for non-valid data */
if (!$valid){
$error_msg[]="First Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($lName==""){
$errorMsg[]="Please enter your Last Name";
} else {
$valid = verifyAlphaNum ($lName); /* test for non-valid data */
if (!$valid){
$error_msg[]="Last Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($email==""){
$errorMsg[]="Please enter your Email Address";
} elseif (!verifyEmail($email)){
$errorMsg[]="Correct eMail format is ( example#anysite.com )";
}
if($street==""){
$errorMsg[]="Please enter your Street Address";
} else {
$valid = verifyAlphaNum ($street); /* test for non-valid data */
if (!$valid){
$error_msg[]="Street Address must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($city==""){
$errorMsg[]="Please enter a City";
} else {
$valid = verifyAlphaNum ($city); /* test for non-valid data */
if (!$valid){
$error_msg[]="City must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($state==""){
$errorMsg[]="Please choose a State";
} else {
$valid = verifyAlphaNum ($state); /* test for non-valid data */
}
}
if($errorMsg){
echo "<ul>\n";
foreach($errorMsg as $err){
echo "<li style='color: #ff6666'>" . $err . "</li>\n";
}
echo "</ul>\n";
} else {
mysql_query("INSERT INTO tblWhere (pk_Username, fldFirstName, fldLastName, fldAdminLevel, fldTotalPosts, fldDateJoined, fldEmail) VALUES ('$user', '$fName', '$lName', '4', '0', '$date', '$email')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
mysql_query("INSERT INTO tblLocation (fk_Username, fldStreet, fldCity, fldState, fldZip) VALUES ('$user', '$street', '$city', '$state', '$zip')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
}
mysql_close();
print $user;
EDIT
Here is the full code, maybe this will help?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>CS148 "Where Are You From?" Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="Stephen B. Wakita" />
<meta name='description' content='Form to gather information for CS148 PHP Form Assignment. The javascript functions for validation are from Easy! Designs, LLC easydesigns.net and few by Robert Erickson.'/>
<link rel="stylesheet"
href="mystyle.css"
type="text/css"
media="screen" />
<script src="validation.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
window.onload = Initialize;
function Initialize(){
if (!document.getElementById || !document.createElement || !document.createTextNode)
return;
var objForm = document.getElementById('frmRegister');
objForm.onsubmit= function(){return fblnVerified(this);};
}
function reSetForm(){
document.getElementById('txtFname').style.background='#fff';
document.getElementById('txtLname').style.background='#fff';
document.getElementById('txtEmail').style.background='#fff';
document.getElementById('lstStates').style.background='#fff';
document.getElementById('errors').innerHTML="";
}
function fblnVerified(theForm){
reSetForm();
returnStatus = true;
errorMsg = "";
numErrors = 0;
if (isEmpty(theForm.txtFname.value)) {
document.getElementById('txtFname').style.background='#FF6';
errorMsg += "<li>Please enter your first name.</li>";
numErrors += 1;
returnStatus = false;
}
if (isEmpty(theForm.txtLname.value)) {
document.getElementById('txtLname').style.background='#FF6';
errorMsg += "<li>Please Enter your last name.</li>";
numErrors += 1;
returnStatus = false;
} else if (!isWithinRange(theForm.txtLname.value.length, 2, 45)){
document.getElementById('txtLname').style.background='#FF6';
errorMsg += "<li>Last name must contain at least two characters.</li>";
numErrors += 1;
returnStatus = false;
}
if (isEmpty(theForm.txtEmail.value)) {
document.getElementById('txtEmail').style.background='#FF6';
errorMsg += "<li>Please enter your email address.</li>";
numErrors += 1;
returnStatus = false;
}else if (!isEmailAddress(theForm.txtEmail.value)){
document.getElementById('txtEmail').style.background='#FF6';
errorMsg += "<li>You have entered your email in an invalid format, please use this format: example#example.xxx </li>";
numErrors += 1;
returnStatus = false;
}
if(returnStatus == false){
msg1 = "Your form is incomplete or incorrect. There are " + numErrors + " errors. ";
msg1 += "Please look for the highlighted items.";
msg = "<p>" + msg1 + "</p><ol class='missing' id='errorMessages'></ol>";
document.getElementById('errors').innerHTML = msg;
document.getElementById('errorMessages').innerHTML= errorMsg;
alert(msg1);
window.scrollTo(0,0);
}
return returnStatus;
}
-->
</script>
</head>
<body class="bodycolor">
<div id="content">
<div id="errors">
</div>
<form action="form.php"
method="post"
id="frmWhere">
<fieldset class="wrapper">
<legend>Where are you from?</legend>
<p>Please answer the following survey. Required fields are marked in <span class="required">red</span>.</p>
<fieldset class="intro">
<legend>Please complete the following survey.</legend>
<fieldset class="main">
<legend>Contact Information</legend>
<fieldset class="info">
<label for="txtUser" class="required">Username</label>
<input type="text" id="txtUser" name="txtUser" value="" tabindex="260"
size="30" maxlength="26" onfocus="this.select()" />
<label for="txtFname" class="required">First Name</label>
<input type="text" id="txtFname" name="txtFname" value="" tabindex="261"
size="55" maxlength="45" onfocus="this.select()" />
<label for="txtLname" class="required">Last Name</label>
<input type="text" id="txtLname" name="txtLname" value="" tabindex="262"
size="55" maxlength="45" onfocus="this.select()" />
<label for="txtEmail" class="required">Email</label>
<input type="text" id="txtEmail" name="txtEmail" value="" tabindex="263"
size="55" maxlength="45" onfocus="this.select()" />
<label for="txtstreet" class="required">Street Address</label>
<input type="text" id="txtStreet" name="txtStreet" value="" tabindex="264"
size="55" maxlength="45" onfocus="this.select()" />
<label for="txtCity" class="required">City</label>
<input type="text" id="txtCity" name="txtCity" value="" tabindex="265"
size="55" maxlength="45" onfocus="this.select()" />
<select id="lstStates" name="lstStates" tabindex="266" size="1">
<option value="ZZ">None</option>
<option value="">-- UNITED STATES --</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="DC">Washington, DC</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
<option value="">-- CANADA --</option>
<option value="AB">Alberta</option>
<option value="BC">British Columbia</option>
<option value="MB">Manitoba</option>
<option value="NB">New Brunswick</option>
<option value="NF">Newfoundland and Labrador</option>
<option value="NT">Northwest Territories</option>
<option value="NS">Nova Scotia</option>
<option value="NU">Nunavut</option>
<option value="ON">Ontario</option>
<option value="PE">Prince Edward Island</option>
<option value="PQ">Quebec</option>
<option value="SK">Saskatchewan</option>
<option value="YT">Yukon Territory</option>
<option value="">-- OTHER --</option>
<option value="OT">Other</option>
</select>
<label for="txtZip" class="required">ZIP Code</label>
<input type="text" id="txtZip" name="txtZip" value="" tabindex="267"
size="6" maxlength="6" onfocus="this.select()" />
<fieldset class="buttons">
<legend></legend>
<input type="submit" id="butSubmit" name="butSubmit" value="Submit"
tabindex="991" class="button"/>
<input type="reset" id="butReset" name="butReset" value="Reset Form"
tabindex="993" class="button" onclick="reSetForm()" />
</fieldset>
</fieldset>
</fieldset>
</fieldset>
</form>
</?php
include ("validation_functions.php");
date_default_timezone_set('UTC');
$dbh=mysql_connect('webdb.uvm.edu','swakita','password');
if (!$dbh)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('SWAKITA', $dbh);
if (isset($_POST['butSubmit'])) {
//handle html characters
$user = htmlentities($user, ENT_QUOTES);
$fName = htmlentities($fName, ENT_QUOTES);
$lName = htmlentities($lName, ENT_QUOTES);
$email = htmlentities($email, ENT_QUOTES);
$date = htmlentities($date, ENT_QUOTES);
$street = htmlentities($street, ENT_QUOTES);
$city = htmlentities($city, ENT_QUOTES);
$state = htmlentities($state, ENT_QUOTES);
$zip = htmlentities($zip, ENT_QUOTES);
$errorMsg=array();
// set variables to data from form
$user= mysql_real_escape_string($_POST["txtUser"]);
$fName= mysql_real_escape_string($_POST["txtFname"]);
$lName= mysql_real_escape_string($_POST["txtLname"]);
$email= mysql_real_escape_string($_POST["txtEmail"]);
$date= date(DATE_RFC822);
$street= mysql_real_escape_string($_POST["txtStreet"]);
$city= mysql_real_escape_string($_POST["txtCity"]);
$state= mysql_real_escape_string($_POST["lstStates"]);
$zip= mysql_real_escape_string($_POST["txtZip"]);
// initiate testing procedures for form contents
if($user==""){
$errorMsg[]="Please enter your Username";
} else {
$valid = verifyAlphaNum ($user); /* test for non-valid data */
if (!$valid){
$error_msg[]="Username must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($fName==""){
$errorMsg[]="Please enter your First Name";
} else {
$valid = verifyAlphaNum ($fName); /* test for non-valid data */
if (!$valid){
$error_msg[]="First Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($lName==""){
$errorMsg[]="Please enter your Last Name";
} else {
$valid = verifyAlphaNum ($lName); /* test for non-valid data */
if (!$valid){
$error_msg[]="Last Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($email==""){
$errorMsg[]="Please enter your Email Address";
} elseif (!verifyEmail($email)){
$errorMsg[]="Correct eMail format is ( example#anysite.com )";
}
if($street==""){
$errorMsg[]="Please enter your Street Address";
} else {
$valid = verifyAlphaNum ($street); /* test for non-valid data */
if (!$valid){
$error_msg[]="Street Address must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($city==""){
$errorMsg[]="Please enter a City";
} else {
$valid = verifyAlphaNum ($city); /* test for non-valid data */
if (!$valid){
$error_msg[]="City must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($state==""){
$errorMsg[]="Please choose a State";
} else {
$valid = verifyAlphaNum ($state); /* test for non-valid data */
}
}
if($errorMsg){
echo "<ul>\n";
foreach($errorMsg as $err){
echo "<li style='color: #ff6666'>" . $err . "</li>\n";
}
echo "</ul>\n";
} else {
mysql_query("INSERT INTO tblWhere (pk_Username, fldFirstName, fldLastName, fldAdminLevel, fldTotalPosts, fldDateJoined, fldEmail) VALUES ('$user', '$fName', '$lName', '4', '0', '$date', '$email')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
mysql_query("INSERT INTO tblLocation (fk_Username, fldStreet, fldCity, fldState, fldZip) VALUES ('$user', '$street', '$city', '$state', '$zip')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
}
mysql_close();
print $user;
?>
</body>
</html>
Your code runs the mysql query outside of the POST check, the mysql query runs no matter what because $errorMsg is not being returned.
Move your mysql logic inside the if (isset($_POST['butSubmit'])) { part of your code.
<?php
include ("validation_functions.php");
date_default_timezone_set('UTC');
$dbh=mysql_connect('webdb.uvm.edu','swakita','password');
if (!$dbh)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('SWAKITA', $dbh);
if (isset($_POST['butSubmit'])) {
//handle html characters
$user = htmlentities($user, ENT_QUOTES);
$fName = htmlentities($fName, ENT_QUOTES);
$lName = htmlentities($lName, ENT_QUOTES);
$email = htmlentities($email, ENT_QUOTES);
$date = htmlentities($date, ENT_QUOTES);
$street = htmlentities($street, ENT_QUOTES);
$city = htmlentities($city, ENT_QUOTES);
$state = htmlentities($state, ENT_QUOTES);
$zip = htmlentities($zip, ENT_QUOTES);
$errorMsg=array();
// set variables to data from form
$user= mysql_real_escape_string($_POST["txtUser"]);
$fName= mysql_real_escape_string($_POST["txtFname"]);
$lName= mysql_real_escape_string($_POST["txtLname"]);
$email= mysql_real_escape_string($_POST["txtEmail"]);
$date= date(DATE_RFC822);
$street= mysql_real_escape_string($_POST["txtStreet"]);
$city= mysql_real_escape_string($_POST["txtCity"]);
$state= mysql_real_escape_string($_POST["lstStates"]);
$zip= mysql_real_escape_string($_POST["txtZip"]);
// initiate testing procedures for form contents
if($user==""){
$errorMsg[]="Please enter your Username";
} else {
$valid = verifyAlphaNum ($user); /* test for non-valid data */
if (!$valid){
$error_msg[]="Username must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($fName==""){
$errorMsg[]="Please enter your First Name";
} else {
$valid = verifyAlphaNum ($fName); /* test for non-valid data */
if (!$valid){
$error_msg[]="First Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($lName==""){
$errorMsg[]="Please enter your Last Name";
} else {
$valid = verifyAlphaNum ($lName); /* test for non-valid data */
if (!$valid){
$error_msg[]="Last Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($email==""){
$errorMsg[]="Please enter your Email Address";
} elseif (!verifyEmail($email)){
$errorMsg[]="Correct eMail format is ( example#anysite.com )";
}
if($street==""){
$errorMsg[]="Please enter your Street Address";
} else {
$valid = verifyAlphaNum ($street); /* test for non-valid data */
if (!$valid){
$error_msg[]="Street Address must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($city==""){
$errorMsg[]="Please enter a City";
} else {
$valid = verifyAlphaNum ($city); /* test for non-valid data */
if (!$valid){
$error_msg[]="City must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($state==""){
$errorMsg[]="Please choose a State";
} else {
$valid = verifyAlphaNum ($state); /* test for non-valid data */
}
if($errorMsg){
echo "<ul>\n";
foreach($errorMsg as $err){
echo "<li style='color: #ff6666'>" . $err . "</li>\n";
}
echo "</ul>\n";
} else {
mysql_query("INSERT INTO tblWhere (pk_Username, fldFirstName, fldLastName, fldAdminLevel, fldTotalPosts, fldDateJoined, fldEmail) VALUES ('$user', '$fName', '$lName', '4', '0', '$date', '$email')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
mysql_query("INSERT INTO tblLocation (fk_Username, fldStreet, fldCity, fldState, fldZip) VALUES ('$user', '$street', '$city', '$state', '$zip')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
}
}
mysql_close();
print $user;
?>
</body>
</html>
PHP Mysql won't insert blank rows magically so you may check what you are really trying to INSERT, or using some debug echo $query statements just before your query, or even better using *print_r(debug_backtrace())*