Jump to content

Contact Form with weekly limit


mtb

Recommended Posts

Hi,

 

I wanted to know if it is possible to have multiple contact forms on my blog that basically send questions to different email accounts, but also have a limit of say 5 emails per week to each account.

After the limit of 5 has been sent for that week I can display a message stating the weekly limit has been reached.

I need to this as I am trying to an experts Q&A section but the experts only agree to 5 emails every week and don't want any more emails than that.

I was thinking about using the Contact Form 7 plugin for Wordpress for the multiple email accounts bit but don't really know how to do the weekly limit.

 

Any help with how to do so would be much appreciated.

 

Thanks

Link to comment
Share on other sites

I would approach this by creating a database table to hold submissions from these various forms, and run a cron job weekly to email out a digest of the last five questions to each address. That way if there's a slow week your experts still get (older) questions, and your users don't hit a brick wall when they want to ask something. If you have a little knowledge of PHP/MySQL and cron, I can take you through the process. Of course, someone may have a better idea.

Link to comment
Share on other sites

Hi Pawn,

 

Thanks for the reply.

 

At the moment I am just starting to learn PHP/MYSQL so I would love any help you could provide from that side.

 

As the website is a domestic violence charity what I was thinking about doing was making a weekly limit of 5 questions per expert (as this is what the experts have agreed to do for now) which after receiving the 5 questions a message just says that the weekly limit has been reached and question section will reopen Monday say, and to then have an emergency contact section which I will deal with myself which is always open.

 

Also the different experts will specialise in different areas so I can't really send one experts questions to another expert.

 

Do you think this is doable?

 

THANKS

Link to comment
Share on other sites

Sure. I don't know what your technical level is, so forgive me if some of this is overly explanatory.

 

First, create a table in MySQL to hold the names and emails of the experts. Call it "experts".

 

CREATE TABLE  `experts` (
`expert_id` TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 100 ) NOT NULL ,
`email` VARCHAR( 255 ) NOT NULL ,
`emails_sent` TINYINT NOT NULL DEFAULT  '0'
) ENGINE = MYISAM ;

 

You can do that manually in phpMyAdmin if you have access to that, or execute the SQL directly. Now we have somewhere to hold our data.

 

Next, you may as well create a simple script to insert your data. I'm going to assume you know how to connect to MySQL and select a database.

 

<?php
//
// do the database connection here
//

$experts = array (
    // name => email
    "john doe" => "john@doe.com",
    "foo bar" => "foo@bar.com"
    // include all your experts in the above format
);
// for each of the experts, run an SQL insert statement and execute it
foreach($experts as $val) {
    $sql = "INSERT INTO experts (name, email) VALUES ('".$key."', '".$val."')";
    if(!$query = mysql_query($sql)) {
        echo "Error inserting ".$val."<br />\n";
        exit;
    }
    echo $val." entered successfully.<br />\n";
}
?>

 

We'll want a home for our little application, so you might want to make a directory for us to keep the files. We can integrate it into your site later. Add the database connection and save the above as insert.php in your new dir. Run it from your browser, hopefully everything goes smoothly.

 

Now let's create a simple HTML form and a bit of PHP to send an email when it's submitted. It's important to validate input from a web form, but for now we're going to skip that as it isn't directly relevant. Save the following as index.php within your directory.

 

<?php
if(!empty($_POST['body'])) {
    // Someone submitted the form!
    $test_email = "test@test.com"; // for test purposes, just stick your email in here for now
    $subject = "Automated Email From Your Site"; // customise this
    $message = $_POST['body'];
    // Send an email
    if(mail($test_email, $subject, $message)) {
        $output = "Email sent successfully!";
    } else {
        $output = "An error was encountered processing your request.";
    }
}
?>
<html>
<head><title>Email Test</title></head>
<body>
<?php
if(isset($output)) {
    // return the feedback from form submission
    echo $output."<br /><br />";
}
// show the form
?>
<form name="contact" method="post" action="">
    <fieldset>
    <label for="emailBody">Your Message</label>
    <textarea name="body" id="emailBody"></textarea>
    <input type="submit" name="submit" value="Send Email" />
    </fieldset>
</form>
</body>
</html>

Now, we should have a script that sends ourselves an email when we enter a message and press submit. Try it out.

 

OK – we have a database full of people to email, and a form that emails people. Once all the above is working properly, I'll get into putting them together and incorporating your emails per week restriction.

Link to comment
Share on other sites

Hi Pawn,

 

Thanks again for all your help.

My technical level is still a beginner so all the details were very helpful.

 

I've managed to create the table in MySQL.

I then made the insert.php but so far only the email address are being copied in to the database, is this OK?

The index.php seems to be working fine.

 

Could you please help me with putting everything together and added the weekly limit.

 

THANK YOU

Link to comment
Share on other sites

I'm afraid I don't have time to take you through this, but I've modified the code we've been using to do what you want. Do this:

 

1) Empty your existing experts table ("TRUNCATE TABLE experts").

2) Add a new column to your experts table called "week_start". Field type "TIMESTAMP", default "CURRENT_TIMESTAMP".

2) In insert.php, change the line "foreach($experts as $val) {" to "foreach($experts as $key => $val) {". Run it again and it should work properly. For test purposes, include yourself in the experts list.

3) Replace index.php with the new version below. Save and upload nav.php, also below.

 

<?php

// index.php

// database connection here
// require_once "db.php";

$max_emails_per_week = 5;

if(isset($_GET['id']) && is_numeric($_GET['id'])) {
    // Get the details of the expert with that ID
    $sql = "SELECT * FROM experts WHERE expert_id = ".$_GET['id']." LIMIT 1";
    if(!$query = mysql_query($sql)) {
        echo "Error on line ".__LINE__.". ".mysql_error();
        exit;
    }
    if(mysql_num_rows($query) != 1) {
        $html = "<p>Sorry, there is no expert with that ID. If you have reached this page from a valid link, please contact the webmaster.</p>";
    } else {
        $row = mysql_fetch_assoc($query);
         // Reset the week start date if more than seven days have passed since it was last set
       	$now = time();
        if($now >= strtotime($row['week_start']) + (7 * 24 * 60 * 60)) {
        	$sql = "UPDATE experts SET week_start = '".date('Y-m-d G:i:s')."', emails_sent = 0 WHERE expert_id = ".$_GET['id'];
        	if(!$query = mysql_query($sql)) {
       			echo "Error on line ".__LINE__.". ".mysql_error();
        		exit;
        	}
        	$row['emails_sent'] = 0;
    	}
        // Check how many emails they've received.
        if($row['emails_sent'] >= $max_emails_per_week) {
            // The limit has been reached
            $html = "<h2>Contact form for ".$row['name']."</h2>\n"
            .	    "<p>Sorry, the expert you selected cannot be contacted at this time. Please try again in a few days.</p>";
        } else {            
        $email = $row['email'];
        $html = 
       "<h2>Contact form for ".$row['name']."</h2>\n"
.       "<form name=\"contact\" method=\"post\" action=\"\">\n"
.       "<input type=\"hidden\" name=\"email\" value=\"".$row['email']."\" />\n"
.       "<fieldset>\n"
.       "<label for=\"emailBody\">Your Message</label>\n"
.       "<textarea name=\"body\" id=\"emailBody\"></textarea>\n"
.       "<input type=\"submit\" name=\"submit\" value=\"Send Email\" />\n"
.       "</fieldset>\n"
.       "</form>\n";
        }
    }
} else {
    $html = "<p>Sorry, an error has occured. If you have reached this page from a valid link, please contact the webmaster.</p>";
}

if(!empty($_POST['body'])) {
    // Someone submitted the form!
    $subject = "Automated Email From Your Site"; // customise this
    $message = $_POST['body'];
    $email = $_POST['email'];
    // Send an email
    if(mail($email, $subject, $message)) {
        $output = "Email sent successfully!";
        $sql = "UPDATE experts SET emails_sent = emails_sent + 1 WHERE expert_id = ".$_GET['id'];
	if(!$query = mysql_query($sql)) {
    		echo mysql_error();
    		exit;
	}
    } else {
        $output = "An error was encountered processing your request.";
    }
}
?>
<html>
<head><title>Email Test</title></head>
<body>
<?php
if(isset($output)) {
    // return the feedback from form submission
    echo $output."<br /><br />";
}
// show the form
echo $html;
// debugging
// comment this out of your production code
echo "<br />Emails sent to this expert: ".$row['emails_sent'];
echo "<br />Week started on: ".$row['week_start'];
echo "<br />Emails sent resets on: ".date('Y-m-d G:i:s', strtotime($row['week_start']) + (7 * 24 * 60 * 60));
?>
</body>
</html>

 

<?php

// nav.php

// database connection here
// require_once "db.php";

$sql = "SELECT name, expert_id FROM experts";
if(!$query = mysql_query($sql)) {
    echo "Error on line ".__LINE__.". ".mysql_error();
    exit;
}
echo "<ul>\n";
while($row = mysql_fetch_assoc($query)) {
    echo "<li><a href=\"index.php?id=".$row['expert_id']."\">Contact ".$row['name']."</a></li>\n";
}
echo "</ul>\n";
?>

 

Test the system by accessing nav.php in your browser, clicking on Contact <you> and sending yourself five messages. After the fifth message, you should no longer be able to submit more. After a week, the page will unlock. Hopefully you won't have too many problems!

 

With minimal modifications, you should be able to include nav.php in your main site's navigation area (or wherever you want). Then it's just a matter of styling the form properly and adding your site's header and footer.

 

Good luck!

Link to comment
Share on other sites

Thanks for help, I just encountered the same question. It helps me a lot!

 

I'm afraid I don't have time to take you through this, but I've modified the code we've been using to do what you want. Do this:

 

1) Empty your existing experts table ("TRUNCATE TABLE experts").

2) Add a new column to your experts table called "week_start". Field type "TIMESTAMP", default "CURRENT_TIMESTAMP".

2) In insert.php, change the line "foreach($experts as $val) {" to "foreach($experts as $key => $val) {". Run it again and it should work properly. For test purposes, include yourself in the experts list.

3) Replace index.php with the new version below. Save and upload nav.php, also below.

 

 

<?php// index.php// database connection here// require_once "db.php";$max_emails_per_week = 5;if(isset($_GET['id']) && is_numeric($_GET['id'])) {    // Get the details of the expert with that ID    $sql = "SELECT * FROM experts WHERE expert_id = ".$_GET['id']." LIMIT 1";    if(!$query = mysql_query($sql)) {        echo "Error on line ".__LINE__.". ".mysql_error();        exit;    }    if(mysql_num_rows($query) != 1) {        $html = "<p>Sorry, there is no expert with that ID. If you have reached this page from a valid link, please contact the webmaster.</p>";    } else {        $row = mysql_fetch_assoc($query);         // Reset the week start date if more than seven days have passed since it was last set       	$now = time();        if($now >= strtotime($row['week_start']) + (7 * 24 * 60 * 60)) {        	$sql = "UPDATE experts SET week_start = '".date('Y-m-d G:i:s')."', emails_sent = 0 WHERE expert_id = ".$_GET['id'];        	if(!$query = mysql_query($sql)) {       			echo "Error on line ".__LINE__.". ".mysql_error();        		exit;        	}        	$row['emails_sent'] = 0;    	}        // Check how many emails they've received.        if($row['emails_sent'] >= $max_emails_per_week) {            // The limit has been reached            $html = "<h2>Contact form for ".$row['name']."</h2>\n"            .	    "<p>Sorry, the expert you selected cannot be contacted at this time. Please try again in a few days.</p>";        } else {                    $email = $row['email'];        $html =        "<h2>Contact form for ".$row['name']."</h2>\n".       "<form name=\"contact\" method=\"post\" action=\"\">\n".       "<input type=\"hidden\" name=\"email\" value=\"".$row['email']."\" />\n".       "<fieldset>\n".       "<label for=\"emailBody\">Your Message</label>\n".       "<textarea name=\"body\" id=\"emailBody\"></textarea>\n".       "<input type=\"submit\" name=\"submit\" value=\"Send Email\" />\n".       "</fieldset>\n".       "</form>\n";        }    }} else {    $html = "<p>Sorry, an error has occured. If you have reached this page from a valid link, please contact the webmaster.</p>";}if(!empty($_POST['body'])) {    // Someone submitted the form!    $subject = "Automated Email From Your Site"; // customise this    $message = $_POST['body'];    $email = $_POST['email'];    // Send an email    if(mail($email, $subject, $message)) {        $output = "Email sent successfully!";        $sql = "UPDATE experts SET emails_sent = emails_sent + 1 WHERE expert_id = ".$_GET['id'];	if(!$query = mysql_query($sql)) {    		echo mysql_error();    		exit;	}    } else {        $output = "An error was encountered processing your request.";    }}?><html><head><title>Email Test</title></head><body><?phpif(isset($output)) {    // return the feedback from form submission    echo $output."<br /><br />";}// show the formecho $html;// debugging// comment this out of your production codeecho "<br />Emails sent to this expert: ".$row['emails_sent'];echo "<br />Week started on: ".$row['week_start'];echo "<br />Emails sent resets on: ".date('Y-m-d G:i:s', strtotime($row['week_start']) + (7 * 24 * 60 * 60));?></body></html>

 

 

 

<?php// nav.php// database connection here// require_once "db.php";$sql = "SELECT name, expert_id FROM experts";if(!$query = mysql_query($sql)) {    echo "Error on line ".__LINE__.". ".mysql_error();    exit;}echo "<ul>\n";while($row = mysql_fetch_assoc($query)) {    echo "<li><a href=\"index.php?id=".$row['expert_id']."\">Contact ".$row['name']."</a></li>\n";}echo "</ul>\n";?>

 

 

Test the system by accessing nav.php in your browser, clicking on Contact <you> and sending yourself five messages. After the fifth message, you should no longer be able to submit more. After a week, the page will unlock. Hopefully you won't have too many problems!

 

With minimal modifications, you should be able to include nav.php in your main site's navigation area (or wherever you want). Then it's just a matter of styling the form properly and adding your site's header and footer.

 

Good luck!

 

Link to comment
Share on other sites

  • 3 weeks later...

Hi,

 

Sorry for the late reply, but just wanted to say a massive thank you for all your help, it works brilliantly and does exactly what I needed.

 

Could I just make one final small request. On the contact form could you teach me how to add a text box for say the persons name / subject and dropdown menu say for (Mr, Mrs, Miss,...) that would also be included in the email that is sent.

 

Would really appreciate it!

 

THANK YOU!!!

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.