联系表格下载文件并在数据库中保存信息

时间:2012-08-24 06:06:34

标签: php mysql sql forms contact

为了保持简单,这就是我想要实现的目标。

  1. 用户填写表格
  2. 如果填写正确,则验证字段
  3. 提交表单时,检查所有验证,如果没有,则显示错误,如果是,
  4. 将表单详细信息发送到我的电子邮件
  5. 将相同的详细信息存储到mysql数据库中
  6. 显示感谢信息
  7. 从文件夹
  8. 下载pdf文件

    我已经设法完成了所有这些,但我面临一个问题。当用户点击下载按钮而不填写任何内容时,他们会收到错误但是会向数据库添加一个空行。如果他们填写不正确的表单,他们仍然会看到错误,但现在数据库中有2行。如果他们正确填写所有内容,他们会看到感谢您的消息,并且还可以下载该文件,但它仍然在表中添加了2行。 我该怎么办呢? :(

    这是index.html的代码

    <!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">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/style.css"/>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript" src="./js/fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
        <script type="text/javascript" src="./js/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
        <link rel="stylesheet" type="text/css" href="./js/fancybox/jquery.fancybox-1.3.4.css" media="screen" />
        <script type="text/javascript">
            $(document).ready(function() {
                $("#download").fancybox({
                    'titlePosition'     : 'inside',
                    'transitionIn'      : 'none',
                    'transitionOut'     : 'none'
                });         
            });
        </script>
    </head>
    
    <body>
    
    <div id="banner" class="clearfix">
        <div class="center">
            <a id="download" class="download" href="#FormLightBox"><img src="img/button-download.png" width="218" height="49" alt="Download" /></a>
            <p>(Your contact details will be required)</p>
        </div>
    </div>
    
    <div style="display: none;">
        <div id="FormLightBox">
            <div class="inner">
    
                <h3 id="status" style="color:#F00; display:none;">Your Errors Here</h3>
                <h3>Leave your details below to download your free Guide pdf file</h3>        
                <p><input type="text" id="name" class="input-text" placeholder="Name"/></p>
                <p><input type="text" id="email" class="input-text" placeholder="E-mail"/></p>
                <p><input type="text" id="postcode" class="input-text" placeholder="Postcode"/></p>
                <p><input type="text" id="phone" class="input-text" placeholder="Telephone" onkeypress="return validnum(event)" /></p>
                <p><input type="image" id="i" class="input-button" src="img/button-download-lager.png" onclick="getResponse()"/></p>
    
            </div>
        </div>
    </div>
    <script type="text/javascript">
        function get(y){
            return document.getElementById(y).value;
        }
        function getResponse(){
            $.get("process.php", { name: get('name'), email: get('email'), postcode: get('postcode'), phone: get('phone') },
               function(data){
                 if(data.status === false || data.status === 'false'){
                     return errorMsg(data.message);
                 }else{
                    errorMsg(data.message);
                    setTimeout(" offerDownloadAndClose()", 4000); 
                 }
               }, "json");
        }
        function errorMsg(msg){
            $('#status').html(msg);
            $('#status').slideDown('slow');
            setTimeout("doHide('#status')", 3000);
        }
        function doHide(t){
            $(t).slideUp('slow');   
        }
        function offerDownloadAndClose(){
            doHide('#fancybox-wrap, #fancybox-overlay');
            window.location = 'process.php?file=true';
        }
        function validnum(evt){
            var charCode;
            charCode = (evt.which) ? evt.which : event.keyCode;
            if ((charCode >= 48 && charCode <= 57) || charCode == 46 || charCode == 127 || charCode == 8)
            {
                return true;
            }
            else{
                return false;
            }
        }
    </script>
    </body>
    </html>
    

    这是我的process.php

     <?php error_reporting(0);
    
    if(empty($_GET)){
        echo json_encode(array('status'=> false, 'message' => 'Please Fill the complete form'));    
        exit;
    }
    //database insertion
    $con = mysql_connect("localhost","mysql_user","mysql_pwd");
    if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("mysql_database", $con);
    $sql="INSERT INTO formdata (name, email, postcode, phone) VALUES ('$_GET[name]','$_GET[email]','$_GET[postcode]','$_GET[phone]')";
    if (!mysql_query($sql,$con))
    {
    die('Error: ' . mysql_error());
    }
    mysql_close($con);
    
    // download function
    if(isset($_GET['file'])){
    $filename = 'Guide.pdf'; // set absolute relative path to this file
    $path = $_SERVER['DOCUMENT_ROOT']."/download/";
    $fullpath = $path.$filename;
    // required for IE, otherwise Content-disposition is ignored
    if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');
    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); // required for certain browsers
    header("Content-Transfer-Encoding: binary");
    header("Content-Type: application/pdf");
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    header("Content-Length: ".filesize($fullpath));
    readfile($fullpath);
    }
    
    if(!isset($_GET['name']) || empty($_GET['name'])){
        echo json_encode(array('status'=> false, 'message' => 'Please Fill the name'));
        exit;
    }elseif(strlen($_GET['name']) < 3){
        echo json_encode(array('status'=> false, 'message' => 'Please Fill the valid name (minimum 3 cherecters)'));
        exit;
    }
    if(!isset($_GET['email']) || empty($_GET['email'])){
        echo json_encode(array('status'=> false, 'message' => 'Please Fill the email'));
        exit;
    }elseif(!ereg('[A-Za-z0-9_-]+\@[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+', $_GET['email'])){
        echo json_encode(array('status'=> false, 'message' => 'Invalid email address'));
        exit;
    }
    if(!isset($_GET['postcode']) || empty($_GET['postcode']) || strlen($_GET['postcode']) < 3){
        echo json_encode(array('status'=> false, 'message' => 'Please Fill the postcode'));
        exit;
    }
    if(!isset($_GET['phone']) || empty($_GET['phone']) || strlen($_GET['phone']) < 11){
        echo json_encode(array('status'=> false, 'message' => 'Please Fill the phone'));
        exit;
    }elseif(strlen(str_replace(' ', '',$_GET['phone'])) > 11){
        echo json_encode(array('status'=> false, 'message' => 'Please Fill with valid (max)11 digit phone number excluding spaces'));
        exit;
    }
    
    $to      = 'name@domain.com';
    $subject = 'Guide has been downloaded';
    $message = "Some one at your website just downloaded the guide with following details. \r\n \r\n";
    $message .= 'Name: '.$_GET['name']." \r\n";
    $message .= 'Email: '.$_GET['email']." \r\n";
    $message .= 'PostCode: '.$_GET['postcode']." \r\n";
    $message .= 'Phone: '.$_GET['phone']." \r\n";
    
    $headers = 'From: '.$_GET['email']. "\r\n" .
        'Reply-To: '.$_GET['email']. "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    
    mail($to, $subject, $message, $headers);
        echo json_encode(array('status'=> true, 'message' => 'Thank You'));
        exit;
    ?>
    

    如果有人可以指出问题并帮我解决这个问题,请非常感谢。 感谢。

1 个答案:

答案 0 :(得分:0)

在您的代码中:您告诉它将数据输入到与检查无关的数据库中。 除了数据库插入的位置之外,我没有更改任何代码。其他任何错误都没有得到解决

<?php error_reporting(0); 

if(empty($_GET)){ 
    echo json_encode(array('status'=> false, 'message' => 'Please Fill the complete form'));     
    exit; 
} 

// download function 
if(isset($_GET['file'])){ 
$filename = 'Guide.pdf'; // set absolute relative path to this file 
$path = $_SERVER['DOCUMENT_ROOT']."/download/"; 
$fullpath = $path.$filename; 
// required for IE, otherwise Content-disposition is ignored 
if(ini_get('zlib.output_compression')) 
ini_set('zlib.output_compression', 'Off'); 
header("Pragma: public"); // required 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Transfer-Encoding: binary"); 
header("Content-Type: application/pdf"); 
header('Content-Disposition: attachment; filename="'.$filename.'"'); 
header("Content-Length: ".filesize($fullpath)); 
readfile($fullpath); 
} 

if(!isset($_GET['name']) || empty($_GET['name'])){ 
    echo json_encode(array('status'=> false, 'message' => 'Please Fill the name')); 
    exit; 
}elseif(strlen($_GET['name']) < 3){ 
    echo json_encode(array('status'=> false, 'message' => 'Please Fill the valid name (minimum 3 cherecters)')); 
    exit; 
} 
if(!isset($_GET['email']) || empty($_GET['email'])){ 
    echo json_encode(array('status'=> false, 'message' => 'Please Fill the email')); 
    exit; 
}elseif(!ereg('[A-Za-z0-9_-]+\@[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+', $_GET['email'])){ 
    echo json_encode(array('status'=> false, 'message' => 'Invalid email address')); 
    exit; 
} 
if(!isset($_GET['postcode']) || empty($_GET['postcode']) || strlen($_GET['postcode']) < 3){ 
    echo json_encode(array('status'=> false, 'message' => 'Please Fill the postcode')); 
    exit; 
} 
if(!isset($_GET['phone']) || empty($_GET['phone']) || strlen($_GET['phone']) < 11){ 
    echo json_encode(array('status'=> false, 'message' => 'Please Fill the phone')); 
    exit; 
}elseif(strlen(str_replace(' ', '',$_GET['phone'])) > 11){ 
    echo json_encode(array('status'=> false, 'message' => 'Please Fill with valid (max)11 digit phone number excluding spaces')); 
    exit; 
} 

$to      = 'name@domain.com'; 
$subject = 'Guide has been downloaded'; 
$message = "Some one at your website just downloaded the guide with following details. \r\n \r\n"; 
$message .= 'Name: '.$_GET['name']." \r\n"; 
$message .= 'Email: '.$_GET['email']." \r\n"; 
$message .= 'PostCode: '.$_GET['postcode']." \r\n"; 
$message .= 'Phone: '.$_GET['phone']." \r\n"; 

$headers = 'From: '.$_GET['email']. "\r\n" . 
    'Reply-To: '.$_GET['email']. "\r\n" . 
    'X-Mailer: PHP/' . phpversion(); 

mail($to, $subject, $message, $headers); 
    echo json_encode(array('status'=> true, 'message' => 'Thank You')); 
//database insertion 
$con = mysql_connect("localhost","mysql_user","mysql_pwd"); 
if (!$con) 
{ 
die('Could not connect: ' . mysql_error()); 
} 
mysql_select_db("mysql_database", $con); 
$sql="INSERT INTO formdata (name, email, postcode, phone) VALUES ('$_GET[name]','$_GET[email]','$_GET[postcode]','$_GET[phone]')"; 
if (!mysql_query($sql,$con)) 
{ 
die('Error: ' . mysql_error()); 
} 
mysql_close($con); 

?>