php email current page - php

I have made an ordering system that right now goes from the product form to a review page. I have the page set up to use PHP loops to show what products they selected form the prior page and it works great. Now I need to have a "order" button that emails the order on. I the practice of writing less code, I would like to not have to re write all the code to email this form on another php form. Is there a way to have email headers on this page and dump the generated html into the body of the email to send?
Here is how I loop the form contents from the previous page. Basically it goes though all the products and if its there, show them on the review. If not, dont.
for ($i=0; $i<8; $i++) {
if (!empty($_REQUEST['driver'][$i]['select'])) {
//add the club to the total of clubs
$club = $_REQUEST['driver'][$i]['select'];
array_push($club_total, $club);
//add the price to the cost
list($shaft, $price) = explode(":", $_REQUEST['driver'][$i]['shaft']);
array_push($cost, $price);
//show the user
echo '<h3>' .$_POST['driver'][$i]['name']. ' - $'. money_format('%i', $price).'</h3>';
echo '<ul>';
if (!empty($_REQUEST['driver'][$i]['left'])) {
echo '<li><strong>Left Handed</strong></li>';
}
echo '<li>Length: '.$_POST['driver'][$i]['length']. '"</li>';
echo '<li>Shaft: '.$shaft. '</li>';
if (!empty($_REQUEST['driver'][$i]['hossel'])) {
echo '<li>Purist Hossel: ' .$_POST['driver'][$i]['hossel'].'</li>';
}
if (!empty($_REQUEST['driver'][$i]['color'])) {
echo '<li>Purist Color: ' .$_POST['driver'][$i]['color'].'</li>';
}
echo '</ul>';
}

You could capture your html in the output buffer, then store it in a variable for later use (as in, putting it into the body of an email).
ob_start();
for ($i=0; $i<8; $i++) {
// ... your code
}
$my_html = ob_get_contents();
ob_end_clean();
then put $my_html as your email body and send it along.
The idea of putting it all in a variable the first time around also works, but this might save you some effort of rewriting everything.

Instead of echoing out the html, build up a string, so $out .= "your html" etc, then you can easily set that lump of html to the body of the email function.
I am assuming you know how to code that, else I'll add code example for you.

Related

PHP: Hide Form after validation (class)

I have a form that is mostly generated by a class named "buildform".
Now every part of the form validates itself on the position it is.
This looks like this:
echo $frm->create_input("customer_nr", "Customer Nr.", "text:empty:int");
The third attribute here are the conditions (here: text field, not empty only integer).
The function "create_input" calls some more function that are validating the form field directly on place when the form is submitted.
I do it this way for multiple reasons:
I can directly color the forms to red when there's an error
I only have to tell the form attributes one time instead of when creating it and validating.
This is really comfortable and until now has made creating forms very easy.
The validation errors for then the users will be stored in a class variable like this:
function add_err($n_errmsg) {
$this->errmsgs[] = $n_errmsg;
return;
}
At the end of the form I show the errors like this:
if(isset($_POST["sbm"])) {
$ret_err = $frm->ret_err();
if(!empty($ret_err)) {
echo $ret_err;
}
else {
// send success mail
}
}
This all works without any problems.
Now I had the idea to hide the form when it's submitted. But then I would have to make sure there are no errors before the form even is loaded!
I wanted to something like
else {
$hideform = true;
// send success mail
}
This currently is not possible as the errors are generated while "generating" the form fields.
If I move the errors to the top the errors are always "empty" there because the validation is done later below...
Do you have an idea how I can solve this?
Do I have to validate the forms before loading them or is there another way?
Thanks!
Best Regards
Toby
Ok, well there are a few ways to solve this.
Basically you are echoing the form html as you go along:
echo $frm->create_input(...);
echo $frm->create_input(...);
what you could do instead is save the html into a string:
$formhtml = '';
$formhtml .= $frm->create_input(...);
$formhtml .= $frm->create_input(...);
if($frm->ret_error()){
echo $formhtml;
//other logic
}else{
//send mail
}
Along the same lines, you could change your form class, so that this is done internaly, and add a show method:
private $html = '';
function create_input(...){
//retrun $ret;
$this->html .= $ret;
function show(){
echo $this->html;
}
$frm->create_input(...);
$frm->create_input(...);
if($frm->ret_error()){
$frm->show();
//other logic
}else{
//send mail
}

PHP counter file and page forwarding

So i'm writing this code so that you either get forwarded to a certain page if you're the first one to hit the link, or you are sent back to the original page after being displayed a message if you're not what beginner mistake am i making?
<?php
$count = file_get_contents('counter.txt');
$count = trim($count);
if ($count="0")
{
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
header("Location: newpage.html");
}
else
{
fclose($fl);
echo "Sorry but the item has already been sold out";
header("Location: oldpage.html");
}
?>
As for the delay, you can accomplish it two different ways. The first is to use PHP header (like you are currently doing), but change it to look like this:
<?php
header("refresh:5;url=oldpage.html");
echo "Sorry but the item has already been sold out";
?>
The other way is to echo out a piece of HTML code, the meta-refresh:
<?php
echo '<meta http-equiv="refresh" content="2;url=oldpage.html">';
echo "Sorry but the item has already been sold out";
?>
In both examples, 5 is the amount of seconds until the refresh. Experiment with each one to see if it will fit your needs.
This might be some sort of syntax that I'm not familiar with, but none of my scripts have ever had the
<? code
I simply use
<?
Also since you did not delay our header tag the user will not see the previously echoed statement above it. It will automatically redirect before the page has time to output fully.

Mail Dynamic Table with Forms via PHP

I have an order form (table) that I need to be sent to an email address.
I understand the basics of how to send an email in PHP, but not the specifics
of this situation (taking the information of the cookie array + form elements and put them in body of the PHP mailer)
I am using this link's answer to store the order form as an array in a cookie
Then I use this javascript to create the table in HTML, inside the #catalog div. The important part is the for loop that makes the table. Using list.items(); one can list the "cookie array" as an array
function loopArrayMail() {
if ($.cookie('productWishlist') == null) {
html = ""; $('#catalog').html(html);
} else {
var cookie = $.cookie("productWishlist"); var items = cookie ? cookie.split(/,/) : new Array();
var html = "<table><tr><th>Product</th><th># to order</th></tr>";
for(var i=0;i<items.length;i++){ html += "<tr><td width='450'>"+items[i]+"</td><td><input type='text' name='numberOfItems' /></td></tr>"; }
html += "</table>"; $('#catalog').html(html);
}}
There is a text input next to each item in the order form for the user to input the # of items they want.
How would I send the contents of the table and each form input as an email in PHP?
My guess is that I'd have to take the cookie array, and with each iteration have an array of all the text inputs and use foreach so that they are together in the email (unsure of how to do this exactly). It is also important that there can be any number of text inputs as the number of items on the order form will increase/decrease.
Here is an example of using foreach to get multiple input boxes, but how might I combine the array from my cookie with the text inputs?
Better you send only plain HTML in the email without any javascript because you won't have any javascript in the email program nor you have any cookies.
No idea who told you you could use that, but Email programs are not Browsers.
However if you send a link via email, any user can then open it in a full-featured internet browser so this might be what you're looking for.
Netscape Communicator 4 had support for javascript in emails, no idea about the cookies.
First you must give the form elements a name followed by [] indicating that it is an array, when you create the form elements in the loopArrayMail() function.
for(var i=0;i<items.length;i++){
html += "<tr><td width='450'>"+items[i]+"</td><td><input type='text' name='ordernum[]' size='8' /></td></tr>";
}
Since the cookie is a string you must first explode the string based on the delimiter which is a comma. Place the two arrays into variables. Then use a for loop to go through all of the array.
function explode_trim($str, $delimiter = ',') {
if ( is_string($delimiter) ) {
$str = trim(preg_replace('|\\s*(?:' . preg_quote($delimiter) . ')\\s*|', $delimiter, $str));
return explode($delimiter, $str);
}
return $str; }
$orderCookie = explode_trim($_COOKIE['productWishlist']);
$orderNum = $_POST['ordernum'];
for ( $i = 0; $i < count($orderCookie); $i++) {
echo $orderCookie[$i] . ' = ' . $orderNum[$i] . '<br />';
}

php processing a dynamically generated form

I'm using php to generate an html page that displays blog/thread items, and I am using javascript to show/hide some of the details. The problem is that I am generating unique IDs for each set of hidden content, which contains a form to process the input. In processing the form, I need to know which blog item was edited - I want to use $_POST. I'm pretty new to javascript, and I'm thinking that there is probably a solution I can use there.
I want the post to save the text to the mysql database (so call one of my php functions that I have working) and tell me what the text was and what the threadId is.
Here is the php code snipet, where $threadDetailItem is an array that has my thread data in it.
foreach ($threadData as $threadDetailItem)
{
// display main line (a bunch of code here ...)
// append button to edit or delete the post for admin
if ( isset ($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == 'Y'){
// edit link opens content, and delete pops up a confirmation box
$el = sprintf ("editThreadLink_%d", $threadDetailItem['blogThreadId']);
$ec = sprintf ("editThreadContent_%d", $threadDetailItem['blogThreadId']);
$link1 = sprintf ("<a id=\"%s\" href=\"javascript:toggle('%s', '%s');\">+</a>", $el, $ec, $el);
$msg .= sprintf ("<li id=\"field6\">%s</li>\n", $link1);
}
$msg .= "</ul>\n";
echo $msg;
// now that the row is printed, lets add the hidden content if admin so they can edit
if ( isset ($_SESSION['isAdmin']) && $_SESSION['isAdmin'] == 'Y'){
// hidden content to enable editing of the posting
$msg = sprintf ("<div id=\"%s\" style=\"display: none\">\n", $ec);
echo $msg;
echo "<form name=\"form\" method=\"post\" action=\"\">\n";
$msg = sprintf ("<textarea id=\"%s\" name=\"%s\">%s</textarea>\n",
$ec, $ec, $threadDetailItem['threadTitle']);
echo $msg;
$msg = sprintf ("<button type=\"submit\"> %s</button>\n", $lang->get('BLOG POST'));
echo $msg;
echo "</form>\n";
echo "</div>";
}
}
Suggestions on good ways to handle this event are much appreciated. Thanks in advance.
The fields in the data are: blogThreadId, threadTitle, username, createdOn, lastUpdated, displayed (not used) and threadDetails (array containing the posting information).
I was able to use $_POST along w/ the ID in a hidden field to enable my php scripts to know which thread was being edited. It is working

Display personal messages list

I have a personal message system in my website done simply with php/sql. Actually I am facing the trouble to display them using jquery. The db has as fields: message_id, message_from, message_to, message_topic, message_subject and message_status. The way I am showing the message_topic is repeating eight times the following:
echo '<table><tr><td>';
retrieve_msg_topic($result);
echo '</td></tr>'; //of course I won't make 8 tables!!!
the function called is:
function retrieve_msg_topic($result)
{
if($row = mysql_fetch_assoc($result))
{
echo $row['usernombre'];
$message_topic = stripslashes($row['message_topic']);
echo '<div id="msg'.$row['message_id'].'">';
echo $message_topic;
echo '</div>';
//this will return: <div id="msgN">message topic (title, commonly subject)</div>
}
} //end function retrieve msg topic
So far I have a list on a table with the last eight messages sent to the user. The following row is reserved for pagination (next/prior page) and, after that, another row showing the message I select from the list presented, like we see in Outlook. Here is my headache. My approach is to call another function (8 times) and have all of them hidden until I click on one of the messages, like this:
echo '<tr><td>';
retrieve_msg_content($result);
retrieve_msg_content($result); //repeat 8 times
echo '</td></tr></table>';
the function this time would be something like this:
function retrieve_msg_content($result)
{
if($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">
$(document).ready(function(){
$("#msg'.$row['message_id'].'").click(function(){
    $(".msgs").hide(1000);
$("#'.$row['message_id'].'").show(1000);
});
});
</script>';
echo '<div class="msgs" id="'.$row['message_id'].'" style="display: none">'
.$row['message_subject'].
'</div>';
}
/* This function returns:
// <script type="text/javascript">
// $(document).ready(function(){
// $("#msgN").click(function(){
// $(".msgs").hide(1000);
// $("#N").show(1000);
// });
// });
// </script>
// <div class="msgs" id="N" style="display: none">Message subject (body of message)</div>
*/
} //end function retrieve msg content/subject
I could simply explain that the problem is that it doesn't work and it is because I do if($row = mysql_fetch_assoc($result)) twice, so for the second time it doesn't have any more values!
The other approach I had was to call both the message_topic and message_subject in the same function but I end up with a sort of accordion which is not what I want.
I hope I was clear enough.
The easiest way to fix your troubles would be to copy the results of the MySQL query into an array
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
And then use that to build your tables.
edit: What I meant was more along the lines of this:
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
echo '<table>';
foreach($yourArray as $i) {
retrieve_msg_topic($i);
}
echo '<tr><td>';
foreach($yourArray as $i) {
retrieve_msg_content($i);
}
echo '</tr></td></table>';
And then removing everything to do with the SQL query from those functions, like this:
function retrieve_msg_topic($result) {
echo '<tr></td>'$result['usernombre'];
echo '<div id="msg'.$result['message_id'].'">';
echo stripslashes($result['message_topic']);
echo '</div><td></tr>';
}
Right now you're doing some weird key mojo with ret[0] being the topic and $ret[1] being the message, which isn't a good practise. Also, I don't see the declaration of $i anywhere in that code.
The error suggests that the result is empty or the query is malformed. I can't be sure from the code I've seen.
A few other notes: it seems weird that you're using stripslashes() on data that's directly from the DB. Are you sure you're not escaping stuff twice when inserting content into the DB?
Always use loops instead of writing something out x times (like the 8 times you said in your question). Think of a situation where you have to change something about the function call (the name, the parameters, whatever). With loops you have to edit 1 place. Without, you need to edit 8 different places.
BTW, another solution to this problem would be using AJAX to load content into the last cell. If you're curious, I could show you how.
more edits:
For AJAX, build your message list as usual and leave the target td empty. Then, add a jQuery AJAX call:
$('MSG_LIST_ELEMENT').click(function() {
var msgId = $(this).attr('id').replace('msg','');
$.get(AJAX_URL+'?msgID='+msgId,function(data) {
$('TARGET_TD').html(data);
})
});
Replace the capitalized variables with the ones you need. As for the PHP, just echo out the contents of the message with the ID $_GET['msgID'].
However, make sure you authenticate the user before echoing out any messages, so that someone else can't read someone's messages by switching the id number. Not sure how authentication works on your site, but this can be done by using session variables.

Categories