Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 06-09-2011, 03:13 AM   PM User | #1
hinrg
New to the CF scene

 
Join Date: Jun 2011
Posts: 8
Thanks: 2
Thanked 0 Times in 0 Posts
hinrg is an unknown quantity at this point
sessions being cleared when adding more items

Hi All,

I have a form which is a list of products being pulled from a database, it displays the product with a checkbox the user can then selected the item they want to enquire about and send them to the contact form the problem is it works fine the the 1st time but if the user goes to select more products the 1st selected products are cleared.

products page
Code:
<?php
include("../../datalogin.php");
include("../../header.php");
?>
  <div id="products-menu">
        <ul>
            <li id="FS"><a href="../../seafood/fish">FRESH FISH</a></li>
            <li id="SC"><a href="../../seafood/scallops">SCALLOPS LIVE</a></li>
            <li id="RO"><a href="../../seafood/roe">FRESH ROE</a></li>
            <li id="MA"><a href="../../seafood/marinated">MARINATED</a></li>
        </ul>
        </div> <!-- end menu -->

 <div id="product_list">
        <form action="/clamms/contact.php" method="post">
        <table align = "center" width = "100%" border="0" style="font-size: 12px; margin-top: 10px; font-family: Tahoma; color: #464646;">
                    <tr>
<?php
                $result_resource = mysql_query("SELECT * FROM products_fresh_fish WHERE stock_category = 'FP' OR stock_category ='FS' ORDER BY stock_description") or die(mysql_error());
                
                    $count = 1; 
                    while($data = mysql_fetch_array($result_resource)) { 
                        if($count % 2 <> 0) { 
                    ?> 
                        <td><?php echo $data['stock_code'] ?></td>
                        <td><input type="checkbox" name="products[]" value="<?php echo $data['stock_description'] ?>" /> <?php echo $data['stock_description'] ?></td>
                        <td><?php echo $data['unit_of_measure'] ?></td>
                                     
                    <?php } else { ?> 
                        
                        <td><?php echo $data['stock_code'] ?></td> 
                        <td><input type="checkbox" name="products[]" value="<?php echo $data['stock_description'] ?>" /> <?php echo $data['stock_description'] ?></td>
                        <td><?php echo $data['unit_of_measure'] ?></td>
                         
                        </tr><tr> 
                         
                    <?php 
                        } 
                        $count++; 
                     }
                     mysql_close($con);
                    ?> 
                 </tr> 
                </table> 
                
                  
                <input type="submit" name="formSubmit" value="Submit Enquiry" />
        </form>
    </div><!-- end products -->
<?php
include("../../footer.php");
?>
contact.php
Code:
<?php
session_start(); 
$your_email ='email@email.com';// <<=== update to your email address

$errors = '';
$name = '';
$visitor_email = '';
$visitor_phone = '';
$user_message = '';

$_SESSION['data'] = $_POST['products'];

function displayProducts()
{
$quote =$_SESSION['data'];

  if(empty($quote)) 
  {
    echo("No products selected.");
  } 
  else 
  {
    $N = count($quote);

    for($i=0; $i < $N; $i++)
    {
      echo ($quote[$i] . "\n" );
      $_SESSION['saveddata'];
    }
  }
}

if(isset($_POST['submit']))
{
	
	$name = $_POST['name'];
	$visitor_email = $_POST['email'];
	$visitor_phone = $_POST['phone'];
	$user_message = $_POST['message'];
	///------------Do Validations-------------
	if(empty($name)||empty($visitor_email)||empty($visitor_phone))
	{
		$errors .= "\n Name, Email and Phone are required fields. ";	
	}
	if(IsInjected($visitor_email))
	{
		$errors .= "\n Bad email value!";
	}
	if(empty($_SESSION['6_letters_code'] ) ||
	  strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
	{
	//Note: the captcha code is compared case insensitively.
	//if you want case sensitive match, update the check above to
	// strcmp()
		$errors .= "\n The captcha code does not match!";
	}
	
	if(empty($errors))
	{
		//send the email
		$to = $your_email;
		$subject="$name completed the web form";
		$from = $visitor_email;
		$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
		
		$body = "A user  $name submitted the contact form:\n".
		"Name: $name\n".
		"Email: $visitor_email \n".
		"Message: \n ".
		"$user_message\n".
		"IP: $ip\n".
		"Item: \n".
		"$quote\n";	
		
		$headers = "From: $from \r\n";
		$headers .= "Reply-To: $visitor_email \r\n";
		
		mail($to, $subject, $body,$headers);
		
		header('Location: thank-you.html');
	}
}

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}
?>
<?php
include("header.php");
?>  
<?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>

<div id='contact_form_errorloc' class='err'></div>
<form id='clamms_contact_form' method="post" name="contact_form" 
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<p>
<label>Name: </label><br />
<input type="text" name="name" size="50" value='<?php echo htmlentities($name) ?>' />
</p>
<p>
<label>Email: </label><br />
<input type="text" name="email" size="50" value='<?php echo htmlentities($visitor_email) ?>' />
</p>
<p>
<label>Phone: </label><br />
<input type="text" name="phone" size="50" value='<?php echo htmlentities($visitor_phone) ?>'/>
</p>
<p>
<label>Message:</label> <br />
<textarea name="message" rows="8" cols="50"><?php echo htmlentities($user_message) ?></textarea>
</p>
<p>
<label>Items of interest:</label> <br />
<textarea name="quote" rows="5" cols="50"><?php echo htmlentities(displayProducts()) ?></textarea>
</p>
<p>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' alt="captach image" />
<br />
<label>Enter the code above here :</label>
<br />
<input id="six_letters_code" name="6_letters_code" type="text" />
<br />
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<input type="submit" value="Submit" name='submit' />
</form>
<script language="JavaScript" type="text/javascript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator  = new Validator("contact_form");
//remove the following two lines if you like error message box popups
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();

frmvalidator.addValidation("name","req","Please provide your name"); 
frmvalidator.addValidation("email","req","Please provide your email"); 
frmvalidator.addValidation("email","email","Please enter a valid email address");
frmvalidator.addValidation("phone","req","Please provide your phone"); 
</script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
	var img = document.images['captchaimg'];
	img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
<noscript>
Code from the <a href='http://www.html-form-guide.com/contact-form/html-contact-form-captcha.html'
>php contact form</a> article.
</noscript>

<?php
include("footer.php");
?>
hinrg is offline   Reply With Quote
Old 06-09-2011, 08:31 AM   PM User | #2
abduraooft
Supreme Master coder!

 
abduraooft's Avatar
 
Join Date: Mar 2007
Location: N/A
Posts: 14,680
Thanks: 158
Thanked 2,182 Times in 2,169 Posts
abduraooft is just really niceabduraooft is just really niceabduraooft is just really niceabduraooft is just really niceabduraooft is just really nice
Quote:
$_SESSION['data'] = $_POST['products'];
That's obvious since your are overwriting the values to the same session variable. Try to use an array notation, like
PHP Code:
$_SESSION['data'][]=$_POST['products']; 
and then check the values at the end using
PHP Code:
print_r($_SESSION['data']); 
__________________
Quote:
The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)

Last edited by abduraooft; 06-09-2011 at 12:50 PM.. Reason: typo, thanks to 'tomharto' for spotting :)
abduraooft is offline   Reply With Quote
Users who have thanked abduraooft for this post:
hinrg (06-10-2011)
Old 06-09-2011, 12:22 PM   PM User | #3
tomharto
Regular Coder

 
Join Date: Jul 2010
Location: Sheffield
Posts: 796
Thanks: 91
Thanked 18 Times in 18 Posts
tomharto is on a distinguished road
Did you mean
PHP Code:
 print_r($_SESSION['data']); 
rather than post?
tomharto is offline   Reply With Quote
Old 06-10-2011, 02:28 AM   PM User | #4
hinrg
New to the CF scene

 
Join Date: Jun 2011
Posts: 8
Thanks: 2
Thanked 0 Times in 0 Posts
hinrg is an unknown quantity at this point
thats works
PHP Code:
(
    [
0] => 
    [
1] => Array
        (
            [
0] => PINEAPPLE CUT SQUID IQF PIECES
            
[1] => SQUID PANKO BOX(4pkt)
            [
2] => SQUID TUBES PENINSULAU5
            
[3] => SQUID TUBES U/10 TOPSAIL
            
[4] => SQUID U/5 TUBES OCEANIC
            
[5] => SQUID TENTICLES large
        
)
 

how do go about foreach the values in the array?

Last edited by hinrg; 06-10-2011 at 05:13 AM..
hinrg is offline   Reply With Quote
Old 06-10-2011, 05:08 AM   PM User | #5
hinrg
New to the CF scene

 
Join Date: Jun 2011
Posts: 8
Thanks: 2
Thanked 0 Times in 0 Posts
hinrg is an unknown quantity at this point
what i'm doing wrong here? rather then getting the products listed it just displays array

PHP Code:
$_SESSION['data'][] = $_POST['products'];

function 
displayProducts()
{
$quote =$_SESSION['data'];
  
  if(empty(
$quote)) 
  {
    echo(
"No products selected.");
  } 
  else 
  {
    
$N count($quote);

    for(
$i=0$i $N$i++)
    {
      echo (
$quote[$i] . "\n" );
    }
  }


Last edited by hinrg; 06-10-2011 at 05:14 AM..
hinrg is offline   Reply With Quote
Old 06-10-2011, 09:50 AM   PM User | #6
tomharto
Regular Coder

 
Join Date: Jul 2010
Location: Sheffield
Posts: 796
Thanks: 91
Thanked 18 Times in 18 Posts
tomharto is on a distinguished road
Im not sure if this is the correct syntax as i cant test it atm but you could use a foreach, its something like this

PHP Code:
$_SESSION['data'][] = $_POST['products'];

function 
displayProducts()

foreach (
$_SESSION['data'] as $item)
{
echo 
$item."<br />";
}

tomharto is offline   Reply With Quote
Users who have thanked tomharto for this post:
hinrg (06-10-2011)
Old 06-10-2011, 10:59 AM   PM User | #7
hinrg
New to the CF scene

 
Join Date: Jun 2011
Posts: 8
Thanks: 2
Thanked 0 Times in 0 Posts
hinrg is an unknown quantity at this point
still doing the same thing

PHP Code:
$_SESSION['data'][] = $_POST['products'];

function 
displayProducts()

foreach (
$_SESSION['data'] as $item)
{
echo 
$item."\n";
}

}

print_r($_SESSION['data']); 
PHP Code:
Array
(
    [
0] => Array
        (
            [
0] => LIVE OYSTERS
            
[1] => LIVE OYSTERS BRUNY ISLAND
        
)
 
    [
1] => Array
        (
            [
0] => ATLANTIC SALMON FILLETS
            
[1] => AUSTRALIAN SALMON
        
)
 

in my text area

PHP Code:
<textarea name="quote" rows="5" cols="50">Array
Array
</
textarea
hinrg is offline   Reply With Quote
Old 06-10-2011, 11:02 AM   PM User | #8
hinrg
New to the CF scene

 
Join Date: Jun 2011
Posts: 8
Thanks: 2
Thanked 0 Times in 0 Posts
hinrg is an unknown quantity at this point
is it also normal that every time i click the page its makes a new empty array?

PHP Code:
Array
(
    [
0] => Array
        (
            [
0] => LIVE OYSTERS
            
[1] => LIVE OYSTERS BRUNY ISLAND
        
)
 
    [
1] => Array
        (
            [
0] => ATLANTIC SALMON FILLETS
            
[1] => AUSTRALIAN SALMON
        
)
 
    [
2] => 
    [
3] => 

hinrg is offline   Reply With Quote
Old 06-10-2011, 11:16 AM   PM User | #9
abduraooft
Supreme Master coder!

 
abduraooft's Avatar
 
Join Date: Mar 2007
Location: N/A
Posts: 14,680
Thanks: 158
Thanked 2,182 Times in 2,169 Posts
abduraooft is just really niceabduraooft is just really niceabduraooft is just really niceabduraooft is just really niceabduraooft is just really nice
Quote:
still doing the same thing
That may be because you are not calling that function displayProducts() anywhere.
__________________
Quote:
The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)
abduraooft is offline   Reply With Quote
Old 06-10-2011, 11:23 AM   PM User | #10
tomharto
Regular Coder

 
Join Date: Jul 2010
Location: Sheffield
Posts: 796
Thanks: 91
Thanked 18 Times in 18 Posts
tomharto is on a distinguished road
Change it to this.

PHP Code:
$_SESSION['data'][] = $_POST['products'];

function 
displayProducts($data)

    foreach (
$data as $item)
    {
        echo 
$item."\n";
    }
}
displayProducts($_SESSION['data']); 
tomharto is offline   Reply With Quote
Old 06-10-2011, 11:23 AM   PM User | #11
hinrg
New to the CF scene

 
Join Date: Jun 2011
Posts: 8
Thanks: 2
Thanked 0 Times in 0 Posts
hinrg is an unknown quantity at this point
Quote:
Originally Posted by abduraooft View Post
That may be because you are not calling that function displayProducts() anywhere.
is this the not the right way to call it?

PHP Code:
<label>Items of interest:</label> <br />
<textarea name="quote" rows="5" cols="50"><?php echo htmlentities(displayProducts()) ?></textarea>
hinrg is offline   Reply With Quote
Old 06-10-2011, 11:27 AM   PM User | #12
tomharto
Regular Coder

 
Join Date: Jul 2010
Location: Sheffield
Posts: 796
Thanks: 91
Thanked 18 Times in 18 Posts
tomharto is on a distinguished road
PHP Code:
$_SESSION['data'][] = $_POST['products'];

function 
displayProducts($data)

    foreach (
$data as $item)
    {
        echo 
$item."\n";
    }
}

echo 
"<label>Items of interest:</label> <br />
<textarea name=\"quote\" rows=\"5\" cols=\"50\">"
.htmlentities(displayProducts($_SESSION['data']))."</textarea>"
tomharto is offline   Reply With Quote
Old 06-10-2011, 11:39 AM   PM User | #13
hinrg
New to the CF scene

 
Join Date: Jun 2011
Posts: 8
Thanks: 2
Thanked 0 Times in 0 Posts
hinrg is an unknown quantity at this point
still just getting this


Array


<label>Items of interest:</label> <br />

top part of my contact.php
PHP Code:
<?php
session_start
(); 
$your_email ='email@email.com';// <<=== update to your email address

$errors '';
$name '';
$visitor_email '';
$visitor_phone '';
$user_message '';
     

$_SESSION['data'][] = $_POST['products']; 

function 
displayProducts($data
{  
    foreach (
$data as $item
    { 
        echo 
$item."\n"
    } 

echo 
"<label>Items of interest:</label> <br /> 
<textarea name=\"quote\" rows=\"5\" cols=\"50\">"
.htmlentities(displayProducts($_SESSION['data']))."</textarea>";
even when i do it this way i get array
PHP Code:
<?php
session_start
(); 
$your_email ='email@email.com';// <<=== update to your email address

$errors '';
$name '';
$visitor_email '';
$visitor_phone '';
$user_message '';
     

$_SESSION['data'][] = $_POST['products']; 

function 
displayProducts($data
{  
    foreach (
$data as $item
    { 
        echo 
$item."\n"
    } 



if(isset(
$_POST['submit']))
{
    
    
$name $_POST['name'];
    
$visitor_email $_POST['email'];
    
$visitor_phone $_POST['phone'];
    
$user_message $_POST['message'];
    
///------------Do Validations-------------
    
if(empty($name)||empty($visitor_email)||empty($visitor_phone))
    {
        
$errors .= "\n Name, Email and Phone are required fields. ";    
    }
    if(
IsInjected($visitor_email))
    {
        
$errors .= "\n Bad email value!";
    }
    if(empty(
$_SESSION['6_letters_code'] ) ||
      
strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
    {
    
//Note: the captcha code is compared case insensitively.
    //if you want case sensitive match, update the check above to
    // strcmp()
        
$errors .= "\n The captcha code does not match!";
    }
    
    if(empty(
$errors))
    {
        
//send the email
        
$to $your_email;
        
$subject="$name completed the web form";
        
$from $visitor_email;
        
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
        
        
$body "A user  $name submitted the contact form:\n".
        
"Name: $name\n".
        
"Email: $visitor_email \n".
        
"Message: \n ".
        
"$user_message\n".
        
"IP: $ip\n".
        
"Item: \n".
        
"$quote\n";    
        
        
$headers "From: $from \r\n";
        
$headers .= "Reply-To: $visitor_email \r\n";
        
        
mail($to$subject$body,$headers);
        
        
header('Location: thank-you.html');
    }
}

// Function to validate against any email injection attempts
function IsInjected($str)
{
  
$injections = array('(\n+)',
              
'(\r+)',
              
'(\t+)',
              
'(%0A+)',
              
'(%0D+)',
              
'(%08+)',
              
'(%09+)'
              
);
  
$inject join('|'$injections);
  
$inject "/$inject/i";
  if(
preg_match($inject,$str))
    {
    return 
true;
  }
  else
    {
    return 
false;
  }
}
?>
<?php
include("header.php");
?>  
<?php
if(!empty($errors)){
echo 
"<p class='err'>".nl2br($errors)."</p>";
}
?>

<div id='contact_form_errorloc' class='err'></div>
<form id='clamms_contact_form' method="post" name="contact_form" 
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<p>
<label>Name: </label><br />
<input type="text" name="name" size="50" value='<?php echo htmlentities($name?>' />
</p>
<p>
<label>Email: </label><br />
<input type="text" name="email" size="50" value='<?php echo htmlentities($visitor_email?>' />
</p>
<p>
<label>Phone: </label><br />
<input type="text" name="phone" size="50" value='<?php echo htmlentities($visitor_phone?>'/>
</p>
<p>
<label>Message:</label> <br />
<textarea name="message" rows="8" cols="50"><?php echo htmlentities($user_message?></textarea>
</p>
<p>
<label>Items of interest:</label> <br />
<textarea name="quote" rows="5" cols="50"><?php echo htmlentities(displayProducts($_SESSION['data'])) ?></textarea>
</p>
<p>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' alt="captach image" />
<br />
<label>Enter the code above here :</label>
<br />
<input id="six_letters_code" name="6_letters_code" type="text" />
<br />
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</p>
<input type="submit" value="Submit" name='submit' />
</form>
<script language="JavaScript" type="text/javascript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator  = new Validator("contact_form");
//remove the following two lines if you like error message box popups
frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();

frmvalidator.addValidation("name","req","Please provide your name"); 
frmvalidator.addValidation("email","req","Please provide your email"); 
frmvalidator.addValidation("email","email","Please enter a valid email address");
frmvalidator.addValidation("phone","req","Please provide your phone"); 
</script>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
    var img = document.images['captchaimg'];
    img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
<noscript>
Code from the <a href='http://www.html-form-guide.com/contact-form/html-contact-form-captcha.html'
>php contact form</a> article.
</noscript>

<?php
include("footer.php");
?>
hinrg is offline   Reply With Quote
Old 06-10-2011, 11:49 AM   PM User | #14
tomharto
Regular Coder

 
Join Date: Jul 2010
Location: Sheffield
Posts: 796
Thanks: 91
Thanked 18 Times in 18 Posts
tomharto is on a distinguished road
Try doing some debugging, echo of $_POST['products'] to see what that contains, print_r the session array to make sure it has the correct info inside it. Look at the manual for the foreach loop as i might have missed something from it.
tomharto is offline   Reply With Quote
Old 06-10-2011, 11:56 AM   PM User | #15
hinrg
New to the CF scene

 
Join Date: Jun 2011
Posts: 8
Thanks: 2
Thanked 0 Times in 0 Posts
hinrg is an unknown quantity at this point
thanks for your help i'll take a break and look at it tomorrow feel fried atm
hinrg is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 08:51 AM.


Advertisement
Log in to turn off these ads.