Jump to content

passing SESSION variables to a MYSQL database !!!help!!!


The Diabolical

Recommended Posts

Hola,

 

I'm trying to create a web form to insert info into my database using session variables. I'm at my wits end at this point. The reset button does its job but when you click submit it doesn't do anything. I'm using the template from the lynda.com essential php web form tutorials. Any help would be appreciated

 

Here is the client-side header code I'm working with,

 

<?php
header("Expires: Thu, 17 May 2001 10:17:17 GMT");    // Date in the past
  	header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header ("Cache-Control: no-cache, must-revalidate");  // HTTP/1.1
header ("Pragma: no-cache");                          // HTTP/1.0
session_start();

if (!isset($_SESSION['SESSION'])) require ( "include/session_init.php");

$arVal = array();
require_once("include/session_funcs1.php");

// make sure the seesion vars are initialized...
reset ($arVal);
while (list ($key, $val) = each ($arVal)) {
	if (!isset($_SESSION[$key])) $_SESSION[$key] = "";
}

if ($_SESSION["eventgenre_sel"] == "") $_SESSION["eventgenre_sel"] = 0; 

// if the bFlg is true then some validation problems in the data.
// namely a blank field or a submission without the feedback page.
// just present a general error...

$flg = "";
$error = "";
if (isset($HTTP_GET_VARS["flg"])) $flg = $HTTP_GET_VARS["flg"];

switch ($flg) {
	case "red":
		$error = "<br><font class=\"txt12_red\">Please fill out all the required fields.<br>Please Try Again.<BR></font>";
		break;
	case "blue":
		$error = "<br><font class=\"txt12_red\">Your Session has Expired.<br>Please Try Again.</font><BR>";
		break;
	case "pink":
		$error = "<br><font class=\"txt12_red\"><BR>The Special Code you entered is not valid.<br>Please Try Again or Leave that field blank.</font><BR>";
		break;
	case "white":
		$error = "<br><font class=\"txt12_red\"><BR>The fields are too long for our Database.<br>Please correct your data via this form.</font><BR>";
		break;
	default:
		$error = "";
}

?>

<?php  echo $_SERVER['SCRIPT_NAME']."<BR>"; ?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


<link rel="stylesheet" type="text/css" href="detect800.css"/>
<link rel="stylesheet" type="text/css" href="detect1024.css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="detect.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/ui.all.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js" type="text/javascript"></script>
<script src="jquery.ui.datetimepicker.js" type="text/javascript"></script>
<script type="text/javascript">
     $(function() {
        $('#eventdate').datetimepicker();
     });
</script> 
<script src="imageflow.js" type="text/javascript"></script>
<script src="highslide-full.js" type="text/javascript"></script>
<script src="autosuggest.js" type="text/javascript"></script>
<script type="text/javascript">
hs.graphicsDir = 'graphics/';
</script>

<script language="javascript">
function SubmitForm() {
	var form = document.forms[0];
	var bRequired = true;
	if((form.eventname.value.length < 1) ||
	(form.eventvenue.value.length < 1) ||
	(form.eventdate.value.length < 1) ||
	(form.eventgenre.value.length < 1) ||
	(form.eventprice.value.length < 1) ||
	(form.eventpromoter.value.length < 1) ||
	(form.eventflyer.value.length < 1)) {
		alert("Please fill out all the required fields.");
		bRequired = false;
	}

	if (!bRequired) return false;

	form.eventgenre_sel.value = form.state.selectedIndex;

	form.submit();
}

function ResetForm() {
	var form = document.forms[0];
	form.eventname.value = "";
	form.eventvenue.value = "";
	form.eventdate.value = "";
	form.eventgenre.value = "";
	form.eventprice.value = "";
	form.eventpromoter.value = "";
	form.eventflyer.value = "";

	form.eventgenre_sel.value = "";
}

</script>
</head>

 

This is the client side form code

<form action="scripts/register.php" method="post" name="userevent" id="userevent">
     <input name="eventgenre_sel" type="hidden" id="eventgenre_sel" value="<?php echo $_SESSION['eventgenre_sel'] ?>" />

<?php echo $error; ?>

<fieldset>
<label for="eventname" accesskey="n" ><span>Event Name</span>
<input type="text" name="eventname" id="eventname" value="<?php echo $_SESSION['eventname_sel']  ?>" size="32" maxlength="30" /></label>

<div id="autosuggest"><ul><li></li></ul></div>
<label for="eventvenue" accesskey="v" ><span>Event Venue</span>
<input type="text" name="eventvenue" id="eventvenue" size="32" value="<?php echo $_SESSION['eventvenue']  ?>" maxlength="30" /></label>

<script type="text/javascript">
var venues = new Array("Republik", "HiFi Club", "Bamboo Tiki Room", "Tantra", "Jubilee Auditorium", "Ironwood Stage & Grill", "Broken City", "Soda", "Amsterdam Rhino", "Olympic Plaza", "Stampede Casino", "Habitat Living Sound", "Cantos Music Foundation", "Flames Central", "Prince's Island Park", "Beat Niq Jazz & Social Club", "Giuseppe's Italian Market", "BLVD", "Fourth on 4th", "Opus on 8th", "Local 510", "Local 522", "Raw Bar", "Jupiter Restaurant & Bar", "Vern's", "Lord Nelson's", "Kings Head Pub", "Blind Beggar Pub", "Viscous Circle", "Milk Tiger Lounge", "Pengrowth Saddledome", "Tubby Dog", "Marquee Room", "Distillery Public House", "Cafe Koi", "Mikey's Juke Joint & Eatery", "Palomino", "Atlantic Trap & Gill", "Drake Inn", "Radiopark Music Room", "Rusty Cage South", "Big Al's Good Times Bar", "Rose & Crown", "Tudor Rose Pub", "Elbow River Casino & Lounge", "Rusty Cage Central", "Rusty Cage South", "Rusty Cage North", "Olive Grove", "Shamrock Hotel", "Woody's Taphouse Southland", "Woody's Taphouse Country Hills", "Murrieta's West Coast Bar & Grill", "Stageline Saloon", "Pig & Pint", "Ranchman's", "Red Pepper Pub", "Stavro's Steak House & Lounge Ranchlands", "Stageline Saloon", "Whiskey");
new AutoSuggest(document.getElementById("eventvenue"),venues);
</script>

<label for="eventdate" accesskey="d" ><span>Event Date</span>
<input type="text" name="eventdate" id="eventdate" value="<?php echo $_SESSION['eventdate']  ?>" size="32" maxlength="30" /></label>

<label for="eventgenre" accesskey="g" ><span>Event Genre</span>
<select name="eventgenre" id="eventgenre">
<option value="none">--select one--</option>
<option value="HipHop">Hip-Hop</option>
<option value="Funk">Funk</option>
<option value="Soul">Soul</option>
<option value="Metal">Metal</option>
<option value="Punk">Punk</option>
<option value="Blues">Blues</option>
<option value="Jazz">Jazz</option>
<option value="Trance">Trance</option>
<option value="Breaks">Breaks</option>
<option value="Electro">Electro</option>
<option value="House">House</option>
<option value="DNB">Drum'N'Bass</option>
<option value="Dubstep">Dubstep</option>
<option value="Lounge">Lounge</option>
<option value="Top40">Top 40</option>
</select>
</label>

<label for="eventprice" accesskey="p" ><span id="eventprice">Event Price</span>
<input type="text" name="eventprice" id="eventprice" value="<?php echo $_SESSION['eventprice']  ?>" size="6" maxlength="4"/></label>

<label for="eventpromoter" accesskey="c" ><span id="eventpromoter">Event Promoter</span>
<input type="text" name="eventpromoter" id="eventpromoter" value="<?php echo $_SESSION['eventpromoter']  ?>" size="25" maxlength="23"/></label>

<label for="eventflyer" accesskey="f" ><span id="eventflyer">Event Flyer (jpg or png MAX 300kb)</span>
<input type="file" name="eventflyer" id="eventflyer" value="<?php echo $_SESSION['eventflyer']  ?>" size="25" maxlength="23"/></label>



<input type="button" name="Reset" value="Reset" onclick="ResetForm();">                           
<input type="button" name="Submit" value="Submit" onsubmit="return validateForm(this);" onclick="SubmitForm();  return false; " >

</fieldset>
</form>
<script language="javascript">
// set the selection box values...

var form = document.forms[0];
	form.eventgenre.selectedIndex = parseInt("<?php echo $_SESSION['eventgenre_sel'] ?>");

</script>

 

And this is the server-side code.


<?php

$debug = FALSE;

/************************************************************
   Adjust the headers...
************************************************************/
header("Expires: Thu, 17 May 2001 10:17:17 GMT");    // Date in the past
  	header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header ("Cache-Control: no-cache, must-revalidate");  // HTTP/1.1
header ("Pragma: no-cache");                          // HTTP/1.0

/*****************************************************************************
   Check the session details.
   we will store all the post variables in session variables
   this will make it easier to work with the verification routines
*****************************************************************************/
session_start();


if (!isset($_SESSION['SESSION'])) require_once( "include/session_init.php" );

$arVal = array();
require_once("include/session_funcs1.php");

reset ($_POST);
while (list ($key, $val) = each ($_POST)) {
	if ($val == "") $val = "NULL";
	$arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); 
	if ($val == "NULL")
		$_SESSION[$key] = NULL;
	else
		$_SESSION[$key] = $val;

	if ($debug) echo $key . " : " . $arVals[$key] . "<br>";
}

/**********************************************************************************************
   Make sure session variables have been set and then check for required fields
   otherwise return to the registration form to fix the errors.
**********************************************************************************************/

// check to see if these variables have been set...
if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) ||  (!isset($_SESSION["eventgenre"]))
	 || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) {
	 resendToForm("?flg=red");
}
	// form variables must have something in them...
if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") {
	resendToForm("?flg=red");
}

// make sure fields are within the proper range...
if (strlen($_SESSION['eventname']) > 35 || strlen($_SESSION['eventvenue']) > 35
	|| strlen($_SESSION['eventdate']) > 35 || strlen($_SESSION['eventgenre']) > 35 
	|| strlen($_SESSION['eventprice']) > 35 || strlen($_SESSION['eventpromoter']) > 35 
	|| strlen($_SESSION['eventflyer']) > 35 ) {
	resendToForm("?flg=white");
}

/**********************************************************************************************
  Insert into the database...
**********************************************************************************************/

$query = "INSERT INTO td_events (seventname, seventvenue, seventdate, seventgenre, seventprice, seventpromoter, seventflyer) "
	."VALUES (".$arVals['eventname'].", ".$arVals['eventvenue'].", ".$arVals['eventdate'].", ".$arVals['eventgenre']
	.", ".$arVals['eventprice'].", ".$arVals['eventpromoter'].", ".$arVals['eventflyer'].")";

//echo $query;

$result = mysql_query($query) or die("Invalid query: " . mysql_error() . "<br><br>". $query);
$insertid = mysql_insert_id();

	/*** This following function will update session variables and resend to the form so the user can fix errors ***/

function resendToForm($flags) {
		reset ($_POST);
		// store variables in session...
		while (list ($key, $val) = each ($_POST)) {
			$_SESSION[$key] = $val;
		}	
		// go back to the form...
		//echo $flags;
		header("Location: ./user_registration.php".$flags);
		exit;
}

?>
<p>SUCCESS!<br>
  The event was entered in the database!<br>
  You probably want to redirect to a thank you page or send an email to the user for confirmation.<br>
  <br>
  <br>
  Here are the variables...<br>
  
<?php
reset ($arVals);
while (list ($key, $val) = each ($arVals)) {
	echo $key . " : " . $arVals[$key] . "<br>";
}

echo "<br><br>The SQL Statment was:<br>";
echo $query."<br><br><br><br>";
?>
</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>


<?php
/**********************************************************************************************
   
   CREATES THUMBNAIL
   
**********************************************************************************************/

//define a maxim size for the uploaded images
define ("MAX_SIZE","1024"); 
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed, 
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH","500"); 
define ("HEIGHT","650"); 

  // this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and height defined, but without deforming the image
function make_thumb($img_name,$filename,$new_w,$new_h)
{
	//get image extension.
	$ext=getExtension($img_name);
	//creates the new image using the appropriate function from gd library
	if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext))
		$src_img=imagecreatefromjpeg($img_name);

  	if(!strcmp("png",$ext) || !strcmp("PNG",$ext))
		$src_img=imagecreatefrompng($img_name);

	 	//gets the dimmensions of the image
	$old_x=imageSX($src_img);
	$old_y=imageSY($src_img);

	 // next we will calculate the new dimmensions for the thumbnail image
	// the next steps will be taken: 
	// 	1. calculate the ratio by dividing the old dimmensions with the new ones
	//	2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
	//		and the height will be calculated so the image ratio will not change
	//	3. otherwise we will use the height ratio for the image
	// as a result, only one of the dimmensions will be from the fixed ones
	$ratio1=$old_x/$new_w;
	$ratio2=$old_y/$new_h;
	if($ratio1>$ratio2)	{
		$thumb_w=$new_w;
		$thumb_h=$old_y/$ratio1;
	}
	else	{
		$thumb_h=$new_h;
		$thumb_w=$old_x/$ratio2;
	}

  	// we create a new image with the new dimmensions
	$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);

	// resize the big image to the new created one
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 

	// output the created image to the file. Now we will have the thumbnail into the file named by $filename
	if(!strcmp("png",$ext))
		imagepng($dst_img,$filename); 
	else
		imagejpeg($dst_img,$filename); 

  	//destroys source and destination images. 
	imagedestroy($dst_img); 
	imagedestroy($src_img); 
}

// This function reads the extension of the file. 
// It is used to determine if the file is an image by checking the extension. 
function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}
// This variable is used as a flag. The value is initialized with 0 (meaning no error found) 
// and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded.
$errors=0;
// checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
	$image=$_FILES['eventflyer']['name'];
	// if it is not empty
	if ($image) 
	{
		// get the original name of the file from the clients machine
		$filename = stripslashes($_FILES['eventflyer']['name']);

		// get the extension of the file in a lower case format
	 	$extension = getExtension($filename);
		$extension = strtolower($extension);
		// if it is not a known extension, we will suppose it is an error, print an error message 
		// and will not upload the file, otherwise we continue
		if (($extension != "jpg")  && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png"))	
		{
			echo '<h1>Unknown extension!</h1>';
			$errors=1;
		}
		else
		{
			// get the size of the image in bytes
			// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which 
		// the uploaded file was stored on the server
			$size=getimagesize($_FILES['eventflyer']['tmp_name']);
			$sizekb=filesize($_FILES['eventflyer']['tmp_name']);

			//compare the size with the maxim size we defined and print error if bigger
			if ($sizekb > MAX_SIZE*500)
			{
				echo '<h1>You have exceeded the size limit!</h1>';
				$errors=1;
			}

  			//we will give an unique name, for example the time in unix time format
			$image_name=$filename;
			//the new name will be containing the full path where will be stored (images folder)
		 	$newname="flyers/".$image_name;
			$copied = copy($_FILES['eventflyer']['tmp_name'], $newname);
			//we verify if the image has been uploaded, and print error instead
			if (!$copied) 
			{
				echo '<h1>Copy unsuccessfull!</h1>';
				$errors=1;
			}
			else
			{
				// the new thumbnail image will be placed in images/thumbs/ folder
				$thumb_name='flyers/thumb_'.$image_name;
				// call the function that will create the thumbnail. The function will get as parameters 
				// the image name, the thumbnail name and the width and height desired for the thumbnail
				$thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
			}}	}}

  //If no errors registred, print the success message and show the thumbnail image created
if(isset($_POST['Submit']) && !$errors) 
{
	echo "<h1>Thumbnail created Successfully!</h1>";
	echo '<img src="'.$thumb_name.'">';
}
?>

 

 

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.