samedi 18 avril 2015

Adding three new fields in MySQL database for newsletter

I have basic knowledge around PHP and MySQL, but not enough knowledge to create a newsletter from scratch.


I found a newsletter tutorial on GitHub which I liked and I would like to implement that newsletter in my website with some small changes.


I have added three extra fields in the HTML code (full name, phone number and URL)


I would like to add these three fields to the MySQL database when someone subscribes to the newsletter. Currently only signup id, email and sign up date is showing in the MySQL database.


If someone could help me with adding the three new fields in MySQL database, I would appreciate it. Been trying to make the newsletter work for some hours now without any luck.


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://ift.tt/1JbrNSF" 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;
});
});

Aucun commentaire:

Enregistrer un commentaire