Jump to content

PHP and SQL. Variables are not passing to Database.


aleister1987

Recommended Posts

I have created a PHP form which includes validation, however.. everytime  the validation passes, php redirects the form to another page where mysql code is to insert the variables... for some reason the variables are not being sent at all.

 

Any suggestions.

 

page 1

 

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1); ?>
<?php
function VerifyForm(&$values, &$errors) {
   // Do all necessary form verification
   // Validate Model Number
   if (strlen($values['model']) < 4) {
      $errors['model'] = 'Model Number too short';
   } elseif( strlen($values['model']) > 20) {
         $errors['model'] = 'Model Number too long';}
         // Validate Price
         if (is_numeric($values['price']) == 0){
            $errors['price'] = 'No Price has been entered';}
            // Validate Product
            if(($values['product']) == 0){
               $errors['product'] = 'No Product has been selected';}
               // Validate Image
        $imageinfo = getimagesize($_FILES['photo']['tmp_name']);
		if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && isset($imageinfo)){
               $errors['photo'] = 'Image format must be either JPEG or GIF';}
                  // Validate Description
                  if (strlen($values['description']) == 0){
                     $errors['description'] = 'Description is too short';}
                     return (count($errors) == 0);
}
function DisplayForm($values, $errors)
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Test Area</title>
			<link rel="stylesheet" href="test.css" type="text/css" media="screen" />
</head>

<body>
	<div id="container">
		<h1>Add a Product</h1>
			<form method="post" id="customForm" action="" enctype="multipart/form-data">
				<table>
						<tr>
							<td>Model Number:</td>
							<td><input id="model" type="text" size="30" name="model" value="<?php echo htmlentities($values['model']); ?>"/></td>
							<td class="error"><p style="color:#FF0000"><?php echo isset($errors['model']) ? $errors['model'] : ''; ?></p></td>
						</tr>
						<tr>
							<td>Choose a Product:</td>
							<td>
							<select class="product" name="product">
							<option value="0">Please select an option below</option>
							<option value="19lcdtv">19" LCD TV</option>
							<option value="22lcdtv">22" LCD TV</option>
							<option value="26lcdtv">26" LCD TV</option>
							<option value="32lcdtv">32" LCD TV</option>
							<option value="37lcdtv">37" LCD TV</option>
							<option value="37plasmatv">37" Plasma TV</option>
							<option value="3D">3D Technology</option>
							<option value="42lcdtv">42" LCD TV</option>
							<option value="42plasmatv">42" Plasma TV</option>
							<option value="46plasmatv">46" Plasma TV</option>
							<option value="50plasmatv">50" Plasma TV</option>
							<option value="54plasmatv">54" Plasma TV</option>
							<option value="58plasmatv">58" Plasma TV</option>
							<option value="65plasmatv">65" Plasma TV</option>
							<option value="bluraydiscs">Bluray Discs</option>
							<option value="blurayhomecinema">Bluray Home Cinema System</option>
							<option value="blurayplayer">Bluray Player</option>
							<option value="blurayportable">Bluray Portable</option>
							<option value="blurayrecorder">Bluray Recorder</option>
							<option value="breadmaker">Breadmakers</option>
							<option value="cdradio">CD, Radio and Cassette Players</option>
							<option value="convectorheater">Convector Heaters</option>
							<option value="cylindercleaner">Cylinder Cleaner</option>
							<option value="answerphone">DECT Answer Phone</option>
							<option value="phone">DECT Phone</option>
							<option value="fire">Dimplex Fires</option>
							<option value="dishwasher">Dishwashers</option>
							<option value="dvddiscs">DVD Discs</option>
							<option value="dvdplayer">DVD Player</option>
							<option value="dvdportable">DVD Portable</option>
							<option value="dvdrecorder">DVD Recorder</option>
							<option value="epilator">Epilators</option>
							<option value="fanheater">Fan Heaters</option>
							<option value="freezers">Freezers</option>
							<option value="fridgefreezer">Fridge-Freezers</option>
							<option value="hdcamcorder">HD Camcorders</option>
							<option value="hddcamcorder">HDD Camcorders</option>
							<option value="homecinema">Home Cinema System</option>
							<option value="iron">Irons</option>
							<option value="kettle">Kettles</option>
							<option value="beauty">Ladies Shavers/Beauty</option>
							<option value="leads">Leads</option>
							<option value="shaver">Mens Shavers/Grooming</option>
							<option value="microsystem">Microsystems</option>
							<option value="microwavegrill">Microwave (Grill)</option>
							<option value="microwavesolo">Microwave (Solo)</option>
							<option value="microwavecombi">Microwave Combination</option>
							<option value="dvtapes">Mini DV Tapes</option>
							<option value="minisystems">Minisystems</option>
							<option value="pvr">Personal Video Recorder (PVR)</option>
							<option value="projector">Projector</option>
							<option value="pure">Pure Radios</option>
							<option value="fridges">Refridgerators</option>
							<option value="sdcamcorder">SD Camcorders</option>
							<option value="sdcards">SD/SDHC/SDXC Cards</option>
							<option value="straighteners">Straighteners</option>
							<option value="stylishcamera">Stylish Cameras</option>
							<option value="superzoomcamera">Super Zoom Cameras</option>
							<option value="toaster">Toasters</option>
							<option value="tumbledryer">Tumble Dryers</option>
							<option value="uprightcleaner">Upright Cleaner</option>
							<option value="brackets">Wall Bracket</option>
							<option value="washingmachine">Washing Machine</option>
							</select>
							</td>
							<td class="error"><p style="color:#FF0000"><?php echo isset($errors['product']) ? $errors['product'] : ''; ?></p></td>
						</tr>
						<tr>
							<td>Price:</td>
							<td><input id="price" type="text" size="30" name="price" value="<?php echo isset($values['price']) ? $values['price'] : htmlentities($values['price']) ; '';?>"/></td>
							<td class="error"><p style="color:#FF0000"><?php echo isset($errors['price']) ? $errors['price'] : ''; ?></p></td>
						</tr>
						<tr>
							<td>Please upload an Image:</td>
							<td><input id="photo" type="file" size="30" name="photo" value="<?php echo isset($values['photo']) ? htmlentities($values['photo']) : ''; ?>"/></td>
							<td class="error"><p style="color:#FF0000"><?php echo isset($errors['photo']) ? $errors['photo'] : ''; ?></p></td>
						</tr>
						<tr>
							<td valign="top">Description:</td>
							<td>
							<textarea id="description" name="description" cols="" rows=""><?php echo isset($values['description']) ? htmlentities($values['description']) : ''; ?></textarea>
							</td>
							<td class="error"><p style="color:#FF0000"><?php echo isset($errors['description']) ? $errors['description'] : ''; ?></p></td>
						</tr>
						<tr>							
							<td><input id="submit" name="submit" type="submit" value="Submit" /></td>
						</tr>
				</table>
			</form>
	</div>
</body>
</html>
<?php
}
function ProcessForm($values)
{
   //INSERT VARIABLES FROM INSERT_ADD.PHP
   // Replace with actual page or redirect 
   header ("Location: http://www.example.com");
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
   $formValues = $_POST;
   $formErrors = array();
   if (!VerifyForm($formValues, $formErrors))
   DisplayForm($formValues, $formErrors);
   else
   ProcessForm($formValues);
}
else
DisplayForm(null, null);
?>

 

 

 

This is the page which includes database details and insert commands

 

 

<?php

$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

//This is the directory where images will be saved 
$target = "images/"; 
$target = $target . basename( $_FILES['photo']['name']); 

// Get values from form
$model=$_POST['model'];
$product=$_POST['product'];
$description=$_POST['description'];
$price=$_POST['price'];
$photo=($_FILES['photo']['name']); 


// Insert data into mysql
$sql="INSERT INTO $tbl_name(model, product, description, price, photo)VALUES('$model', '$product', '$description', '$price', '$photo')";
$result=mysql_query($sql);

if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
{ 
//Tells you if its all ok 
echo "<center>The file " . basename($_FILES['photo']['name']) . " has been uploaded, and your information has been added to the directory</center>"; 
} 

else { 
//Gives and error if its not 
echo "Sorry, There was a problem Uploading your Details."; 
} 

// close connection
mysql_close();
?>

Link to comment
Share on other sites

In this case, there's really no need for a separate script to process the form and perform the DB insert/update. It can all be done in one script with a couple conditional statements, if desired. Briefly, the logic would be:

 

1) form displayed and filled in

2) if form submitted, validate

3) if validation errors, go back to 1

4) if validation ok, update database, (and possibly redirect to a 'success' page)

Link to comment
Share on other sites

Would this work.

 

This is on the first page.

 

<?php
}
function ProcessForm($values)
{
   // INSERT VARIABLES TO DATABASE 
   include("insert_add.php");
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
   $formValues = $_POST;
   $formErrors = array();
   if (!VerifyForm($formValues, $formErrors))
   DisplayForm($formValues, $formErrors);
   else
   ProcessForm($formValues);
}
else
DisplayForm(null, null);
?>

 

and then the database details

 

<?php

$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

//This is the directory where images will be saved 
$target = "images/"; 
$target = $target . basename( $_FILES['photo']['name']); 

// Get values from form
$model=$_POST['model'];
$product=$_POST['product'];
$description=$_POST['description'];
$price=$_POST['price'];
$photo=($_FILES['photo']['name']); 

// Insert data into mysql
$sql="INSERT INTO $tbl_name(model, product, description, price, photo)VALUES('$model', '$product', '$description', '$price', '$photo')";
$result=mysql_query($sql);

if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
{ 
//redirect user to success page
header('Location: insertproductsuccess.php); 
}
else { 
//Gives and error if its not 
echo "Sorry, There was a problem Uploading your Details, please go back and try again!"; 
} 

// close connection
mysql_close();
?>

 

Thanks

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.