Need Help - how to include session data into a form

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Need Help - how to include session data into a form

Post by Tokunbo »

hello sirs,

Can you please help me with how best to go about this.

For example, I have an index.php page on which a user makes some choices of products, using a pull down menu, etc., I have a cart whereby when a product is chosen and "added". Chosen products are displayed in a so called basket. I store the sessionID, productID and productName in the DB.

To finally submit the order, the user is supposed to fill up his name and email address in a form and click the submit botton.

I coded the form (name, email address) sepately and inserted it on the index page using using an include statement:
<div id="contactus">
<?php include("contactform.php"); ?>
</div>
By itself, the form works, but when I include it on the index page, I want it to send (1) the forms own contents(name, email addr) and (2) the data saved in the DB against the current sessionID of the index page together - as an email.

For example, suppose the user had chosen 3-products and there are 3-products are in the cart, each referenced with sessionID #1234567.

After the user fills up his name and email address, I want the form to send the names of the three products, the filled-in name and email address (5 data in all ) in an email.

Please note, by itself, the form works. It can send the name and email addr entered to the configured email address.

I just need advise on how to include these external data(already captured in reference to a sessionID/#) in the email to be sent.

And pls, just in case the way im going about it is wrong, kindly advise.

thanks
Toks
please advise, how can this be done.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Need Help - how to include session data into a form

Post by social_experiment »

Depending on how the data is stored within the database you can retrieve it and place it inside a variable and pass this along to the mail() function.

Code: Select all

<?php
 // connect to the database and retrieve the information
 // from the db and place it inside mysql_query()
 while ($row = mysql_fetch_array($sql)) {
    $msg = $row['products'];
 }

 mail($to, $subj, $msg, $headers);
?>
Greatly simplified but this should serve as basis on how to achieve what you have in mind;
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Re: Need Help - how to include session data into a form

Post by Tokunbo »

hello there,

thanks for the response. Ive put your suggestion into good use.

My next question will be how do I "unpack" the contents of $msg into rows and columns inside the email, together with other inputs on the form.

On the other hand, I thought it would be better into a file instead for demo purposes since my code isnt online yet.

I sourced up some code on the net for writing into a file, and I can now get this output as a text file "output.txt" after clicking the submit button:
Below is the result of your feedback form. It was submitted on Sunday, April 1st, 2012 at 09:00 PM.
Name : hello
Email : world
Cart : $msg
Submit : Submit
-----------
where "Name" and "Email" are the inputs from my form.

Cart is passed as the hidden variable $msg(your previous reply), unfortunately, it doesnt display the contents from your previous code.
<form id="form1" name="form1" method="post" action="write.php">
Name: <input name="name" type="text" id="name" /><br />
Email: <input name="email" type="text" id="email" /><br />
<input type="hidden" name="cart" value="$msg" />
<input type="submit" name="Submit" value="Submit" />
</form>
How do I get $msg to display into rows and columns in my output-written file.txt. For example, I would want something like this:
1 and 2 are from the form and 3 is the contents of $msg.
======================
1) Name :
2) Email :
3) Cart:
Product1 Quantity1 Description1
Product2 Quantity2 Description2
Product3 Quantity3 Description3
etc
======================
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Need Help - how to include session data into a form

Post by social_experiment »

If the information is retrieved from the database there is no need to pass it along with the form; before sending the email you can retrieve it, place it inside the variable and send the message. The only value you might have to pass along will be the session id (or a unique value to the specific user) which will allow you to retrieve the products from the database.

As for unpacking the items; i forgot to add the concatenation operator the my code snippet; if used in conjunction with the equals symbol (.=) it will append the new data to any existing data; you could place the data inside an array and loop through it. I think this will be an easier option

Code: Select all

<?php
 // connect to the database and retrieve the information
 // from the db and place it inside mysql_query()
 while ($row = mysql_fetch_array($sql)) {
    $msg[] = $row['products'];
 }

 foreach ($msg as $product) {
      // note the use of the concatenation operator (.)
      $mailContent .= $product . "\r\n";
 }

 // to add this to your existing message

 $message = 'Name' . $_POST['name'];
 $message .= $mailContent;
 
 mail($to, $subj, $message, $headers);
?>
You still don't mention how you store the data; each product in it's own row, as a group separated by commas, etc
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Re: Need Help - how to include session data into a form

Post by Tokunbo »

hello there,
sorry for the delayed reply.

1) how I store the data?
I have a DB, then when a user(supposed to) selects a product, and clicks "ADD", the selected product gets added to the basket. If another product is selected, it gets added again. There is also a delete from cart button which deletes items.

In one DB row, I have these SessionID, ProductName, Quantity and Comments.
In another DB row, I have these SessionID, ProductName, Quantity and Comments.

Is this the answer you need as per your below question.

Your below suggestion is apprecaited. I however get an error(Ive tried to resolve it myself) - saying something about an undefined variable, in this line of your code:
$mailContent .= $product . "\r\n";
This is my code:

Code: Select all

<?php
		$query = "SELECT OrderID, Product FROM orderbox_tbl where UserSessionID = '{$userSid}'";
		$result=mysql_query($query);
		$num=mysql_num_rows($result);
	// comment start
	// this section displays cart contents - for test purposes only
	while ($row = mysql_fetch_assoc($result)) 
	{
		echo "<tr>
			<td>".$row['Product']."</td>
		</tr>";
	}
        //this is where your suggestions start
	while ($row = mysql_fetch_array($result)) 
	{
		$msg[] = $row['Product'];
	}
	foreach ($msg as[b] $product[/b]) 
	{
      // note the use of the concatenation operator (.)
      $mailContent .= $product . "\r\n";
	}

	// comment end
// this displays the session ID above the table
	echo $_SESSION['sessID'];

	?>

The error I get is from the variable name in bold. If I remove the whole foreach section, the thing works fine.

What I would want is to write the contents of the cart into a file using $mailContent.

If I can see things working well in the file, then Ill do the mail. 

User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Need Help - how to include session data into a form

Post by social_experiment »

Tokunbo wrote:Is this the answer you need as per your below question.
It does indeed thanks;

This line of code : foreach ($msg as<span style="font-weight: bold"> $product</span>) is causing the issue; it should be

Code: Select all

<?php
 foreach ($msg as $product)
?>
Any styling you wish to apply has to be done when outputting the value
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Re: Need Help - how to include session data into a form

Post by Tokunbo »

hello there,

thanks, the code is correct. I think the error came while I was copying.

what I have is rightly stated as:
foreach ($msg as $product)
and thats where Im getting the error.

Code: Select all

<?php
                $query = "SELECT OrderID, Product FROM orderbox_tbl where UserSessionID = '{$userSid}'";
                $result=mysql_query($query);
                $num=mysql_num_rows($result);
        // comment start
        // this section displays cart contents - for test purposes only
        while ($row = mysql_fetch_assoc($result))
        {
                echo "<tr>
                        <td>".$row['Product']."</td>
                </tr>";
        }
        //this is where your suggestions start
        while ($row = mysql_fetch_array($result))
        {
                $msg[] = $row['Product'];
        }
        foreach ($msg as $product)
        {
      // note the use of the concatenation operator (.)
      $mailContent .= $product . "\r\n";
        }

        // comment end
// this displays the session ID above the table
        echo $_SESSION['sessID'];

        ?>


cheers
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Need Help - how to include session data into a form

Post by social_experiment »

Does the undefined error refer to $mailContent? If so you can try the code below

Code: Select all

<?php
// try using this
if (isset($mailContent)) {
    $mailContent .= $product . "\r\n";
}
else {
    $mailContent = $product . "\r\n";
}
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Re: Need Help - how to include session data into a form

Post by Tokunbo »

hi,

the undefined error message refers to $product
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Need Help - how to include session data into a form

Post by social_experiment »

Tokunbo wrote:the undefined error message refers to $product
Can you paste the error message, I'm baffled just a bit because $product is defined and even if you don't use the code i suggested $mailContent is picked up as undefined; i tried to recreate the problem using this code

Code: Select all

<?php
 // sample 1 gives a undefined error for $mailContent 
 $msg = array('Fee', 'Fi', 'Fo', 'Fum');
 
 foreach ($msg as $product)
 {
      $mailContent .= $product . "\r\n";		
 }
	
echo $mailContent;
Sample two doesn't give any undefined notices

Code: Select all

<?php
$msg = array('Fee', 'Fi', 'Fo', 'Fum');
 
 foreach ($msg as $product)
	{
  // note the use of the concatenation operator (.)
		if (isset($mailContent)) {
			$mailContent .= $product . "\r\n";
		}
		else {
			$mailContent = $product . "\r\n";
		}
	}
	
echo $mailContent;
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Re: Need Help - how to include session data into a form

Post by Tokunbo »

hello there,

Just to let you know that I appreciate your help. I tried your second code, by itself it works. When I add it into mine, the error comes.

heres a screenshot.
error.PNG
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Need Help - how to include session data into a form

Post by Celauran »

$msg is empty, so the foreach fails. Since $mailContent is only defined inside the foreach (which fails) it also doesn't exist. Hence the three errors.

EDIT: I also noticed you're trying to iterate over the same result set twice, which isn't going to work.

Try replacing this:

Code: Select all

<?php

$query = "SELECT OrderID, Product FROM orderbox_tbl where UserSessionID = '{$userSid}'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
// comment start
// this section displays cart contents - for test purposes only
while ($row = mysql_fetch_assoc($result))
{
    echo "<tr>
                        <td>" . $row['Product'] . "</td>
                </tr>";
}
//this is where your suggestions start
while ($row = mysql_fetch_array($result))
{
    $msg[] = $row['Product'];
}
foreach ($msg as $product)
{
    // note the use of the concatenation operator (.)
    $mailContent .= $product . "\r\n";
}

// comment end
// this displays the session ID above the table
echo $_SESSION['sessID'];

?>
With this:

Code: Select all

<?php

$query = "SELECT OrderID, Product FROM orderbox_tbl where UserSessionID = '{$userSid}'";
$result = mysql_query($query);

// Initialize variables
$mailContent = "";
// $msg doesn't seem to serve any purpose, so let's cut out the middleman
// $msg = array();

while ($row = mysql_fetch_array($result))
{
    echo "<tr><td>{$row['Product']}</td></tr>";
    // $msg[] = $row['Product'];
    $mailContent .= "{$product}\r\n";
}
echo $_SESSION['sessID'];

?>
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Re: Need Help - how to include session data into a form

Post by Tokunbo »

hi,

Note: This displays the Product list from the DB
echo "<tr><td>{$row['Product']}</td></tr>";
where is $product defined.

the error msg is Undefined variable $product.
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Re: Need Help - how to include session data into a form

Post by Tokunbo »

hi again,

dont worry, I used it like this instead:
while ($row = mysql_fetch_array($result))
{
echo "<tr><td>{$row['Product']}</td></tr>";
echo "<br/>";
// $msg[] = $row['Product'];
$mailContent .= "{$row['Product']}\r\n";
}
Tokunbo
Forum Commoner
Posts: 46
Joined: Thu Sep 29, 2011 8:53 am

Re: Need Help - how to include session data into a form

Post by Tokunbo »

hi there,

Now things are working. Thank you very much.

But pls I have another question.:

I am able to get the contents of the cart written to a file. But note, ive been using just once column data(Product - product name) for test purposes.

Ideally, I want to write the entire cart (Product, Quantity, and Comments) to a file/email. Could I concatenate all the data into just one variable, and would be able to unpack them later, into rows and columns, or would it best to have:

as per above code: this part:
$mailContent1 .= "{$row['Product']}\r\n";
$mailContent2 .= "{$row['Quantity']}\r\n";
$mailContent3 .= "{$row['Comment']}\r\n";
Pls advise:
Post Reply