在MySQL数据库中添加三个新字段用于简报

时间:2015-04-17 15:25:12

标签: php html mysql ajax newsletter

我掌握有关PHP和MySQL的基本知识,但没有足够的知识从头开始创建新闻稿。

我在Git Hub上找到了一个我喜欢的时事通讯教程,我想在我的网站上实现这个时事通讯,并做了一些小改动。

我在HTML代码中添加了三个额外字段(全名,电话号码和网址)

当有人订阅时事通讯时,我想将这三个字段添加到MySQL数据库中。目前只有注册ID,电子邮件和注册日期显示在MySQL数据库中。

如果有人可以帮我添加MySQL数据库中的三个新字段,我将不胜感激。一直试图使通讯工作几个小时没有任何运气。

INDEX.HTML

<!doctype html>
            <html>
                <head>
                    <meta charset="utf-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1">
                    <title>Ajax Newsletter Form</title>
                    <link href="http://fonts.googleapis.com/css?family=Raleway:300,400,600" rel="stylesheet" type="text/css">
                    <link rel="stylesheet" href="assets/css/style.css">
                </head>
                <body>

                    <div id="newsletterform">
                        <div class="wrap">
                            <h3>Get Email Update</h3>
                            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ullamcorper sapien luctus nisl laoreet, ac commodo tellus placerat. Etiam nec magna lacus. Curabitur quis felis vel nisl tincidunt hendrerit.</p>
                            <form action="send.php" method="post" id="newsletter" name="newsletter">
                                <input type="text" name="full-name" id="full-name" value="" placeholder="Full Name" />
                                <input type="email" name="signup-email" id="signup-email" value="" placeholder="E-mail Address" />
                                <input type="number" name="phone-number" id="phone-number" value="" placeholder="Phone Number" />
                                <input type="url" name="website-url" id="website-url" value="" placeholder="Website URL" />
                                <input type="submit" value="Subscribe" name="signup-button" id="signup-button">
                                <span class="arrow"></span>
                            </form>
                            <div id="response"></div>
                        </div>
                    </div>

                    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
                    <script src="assets/js/lib.js"></script>
                </body>
            </html>

SEND.PHP

<?php
require 'inc/Database.class.php';
require 'inc/Newsletter.class.php';

if (!empty($_POST)) {
  $text = $_POST['full-name'];
  $email = $_POST['signup-email'];
  $number = $_POST['phone-number'];

  Newsletter::register($email, $text, $number);
}

CREATE_TABLE.SQL

 CREATE TABLE `signups` (
   `signups_id` int(10) NOT NULL AUTO_INCREMENT,
   `signup_email_address` varchar(250) DEFAULT NULL,
   `signup_date` datetime DEFAULT NULL,
    PRIMARY KEY (`signups_id`)
  ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

DATABASE.CLASS.PHP

<?php
class Database
{
private static $dbName = 'test_db';
private static $dbHost = 'localhost';
private static $dbUsername = 'test_admin';
private static $dbUserPassword = 'test123';

private static $cont = null;

public function __construct() {
    die('Init function is not allowed');
}

public static function connect() {
    if (null === self::$cont) {
        try {
            self::$cont =  new PDO('mysql:host='.self::$dbHost.'; dbname='.self::$dbName, self::$dbUsername, self::$dbUserPassword);
        } catch(PDOException $e) {
            die($e->getMessage());
        }
    }
    return self::$cont;
}

public static function disconnect() {
    self::$cont = null;
}

}

NEWSLETTER.CLASS.PHP

<?php
class Newsletter
{
private static $email;
private static $datetime = null;

private static $valid = true;

public function __construct() {
    die('Init function is not allowed');
}

public static function register($email) {
    if (!empty($_POST)) {
        self::$email    = $_POST['signup-email'];
        self::$datetime = date('Y-m-d H:i:s');

        if (empty(self::$email)) {
            $status  = "error";
            $message = "The email address field must not be blank";
            self::$valid = false;
        } else if (!filter_var(self::$email, FILTER_VALIDATE_EMAIL)) {
            $status  = "error";
            $message = "You must fill the field with a valid email address";
            self::$valid = false;
        }

        if (self::$valid) {
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $existingSignup = $pdo->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
            $existingSignup->execute();
            $data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;

            if (!$data_exists) {
                $sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
                $q = $pdo->prepare($sql);

                $q->execute(
                    array(':email' => self::$email, ':datetime' => self::$datetime));

                if ($q) {
                    $status  = "success";
                    $message = "You have been successfully subscribed";
                } else {
                    $status  = "error";
                    $message = "An error occurred, please try again";
                }
            } else {
                $status  = "error";
                $message = "This email is already subscribed";
            }
        }

        $data = array(
            'status'  => $status,
            'message' => $message
        );

        echo json_encode($data);

        Database::disconnect();
    }
}
}

LIB.JS

$(document).ready(function () {
$('#newsletter').submit(function () {
    var $this     = $(this),
        $response = $('#response'),
        $mail     = $('#signup-email'),
        testmail  = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
        hasError  = false;

    $response.find('p').remove();

    if (!testmail.test($mail.val())) {
        $response.html('<p class="error">Please enter a valid email</p>');
        hasError = true;
    }

    if (hasError === false) {

        $response.find('p').remove();
        $response.addClass('loading');

        $.ajax({
            type: "POST",
            dataType: 'json',
            cache: false,
            url: $this.attr('action'),
            data: $this.serialize()
        }).done(function (data) {
            $response.removeClass('loading');
            $response.html('<p>'+data.message+'</p>');
        }).fail(function() {
            $response.removeClass('loading');
            $response.html('<p>An error occurred, please try again</p>');
        })
    }


    return false;
});
});

3 个答案:

答案 0 :(得分:1)

这里有很多问题:

SEND.PHP(缺少网址参数)

<?php
require 'inc/Database.class.php';
require 'inc/Newsletter.class.php';

if (!empty($_POST)) {
  $name= $_POST['full-name'];
  $email = $_POST['signup-email'];
  $phone = $_POST['phone-number'];
  $url = $_POST['website-url'];

  Newsletter::register($email, $name, $phone, $url);
}

NEWSLETTER.CLASS.PHP(在寄存器方法中添加您的参数并使用它们)

public static function register($p_email, $p_name, $p_phone, $p_url) {
       self::$email    = $p_email;
       self::$datetime = date('Y-m-d H:i:s');
       self::$name     = $p_name;
       self::$phone   = $p_phone;
       self::$url      = $p_url;

CREATE_TABLE.SQL添加这些列

 CREATE TABLE `signups` (
   `signups_id` int(10) NOT NULL AUTO_INCREMENT,
   `signup_email_address` varchar(250) DEFAULT NULL,
   `signup_date` datetime DEFAULT NULL,
   `signup_url` varchar(250) DEFAULT NULL,
   `signup_name` varchar(100) DEFAULT NULL,
   `signup_phone` varchar(20) DEFAULT NULL,
    PRIMARY KEY (`signups_id`)
  ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

然后将它们添加到您的sql插入中:

    $sql = "INSERT INTO signups (signup_email_address, signup_date, signup_url, signup_name, signup_phone) VALUES (:email, :datetime, :url, :name, :phone)";
    $q = $pdo->prepare($sql);
    $q->execute(
                    array(':email' => self::$email, ':datetime' => self::$datetime), ':url' => self::$url, ':name' => self::$name, ':phone' => self::$phone);

答案 1 :(得分:0)

简单。首先你的Create_table查询将是这样的

CREATE TABLE `signups` (

signups_id int(10)NOT NULL AUTO_INCREMENT,    signup_email_address varchar(250)DEFAULT NULL,    signup_date datetime DEFAULT NULL,     full_name varchar(100)NOT NULL,     phone_number integer(20)NOT NULL,     主要关键(signups_id)   )ENGINE = MyISAM AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;

在第2步中,检查电话号码,注册电子邮件和全名是否必须为空。

        self::$full_name= $_POST['full-name'];
        self::$PhoneNo= $_POST['phone-no'];

在第3步中,在插入查询中进行这些更改

  

$ sql =&#34; INSERT INTO注册(signup_email_address,signup_date,full_name,phone_number)VALUES(:email,:datetime,:full_name,:phoneNo)&#34 ;;

希望你有这个想法

答案 2 :(得分:-1)

在SEND.php中你发送了三个参数但没有在NEWSLETTER.CLASS.PHP中接收

Newsletter::register($email, $text, $number); SEND.php

public static function register($email) { // NEWSLETTER.CLASS.PHP

将其更改为,

public static function register($email, $text, $number) { // NEWSLETTER.CLASS.PHP

然后你需要优化你的查询,

if (!$data_exists) {
            $sql = "INSERT INTO signups (signup_email_address, signup_date, db_field_name, db_field_email,db_field_number) VALUES (:email, :datetime, :any_variable_for_name, :any_variable_for_email, :any_variable_for_number)";
            $q = $pdo->prepare($sql);

            $q->execute(
                array(':email' => self::$email, ':datetime' => self::$datetime, ':any_variable_for_name' => $name, ':any_variable_for_email' => $email, ':any_variable_for_number' => $number));

            if ($q) {
                $status  = "success";
                $message = "You have been successfully subscribed";
            } else {
                $status  = "error";
                $message = "An error occurred, please try again";
            }
        } else {
            $status  = "error";
            $message = "This email is already subscribed";
        }

这可能对你有所帮助。