Tuesday, November 28, 2023
HomeVideo EditingConstruct a Publication System With PHP and MySQL

Construct a Publication System With PHP and MySQL


As we speak, we’re going to be constructing a publication system utilizing PHP with a MySQL background. The tutorial will cowl constructing a system that permits for a number of publication lists and the sending of messages to particular lists.

Hey guys, so we’re going to be constructing a fairly advanced publication system, so lets get began! You will want two assets for the venture.


Step 1: Create the Utility Skeleton

When beginning any venture, I wish to structure the folders earlier than I begin coding, so lets try this now. First, create the general venture listing. Subsequent, create a folder named admin inside your venture folder. Then contained in the admin folder, add two folders names media and swift. Lastly, create a folder named photographs contained in the media listing. Additionally, you possibly can place the Swift lib folder contained in the swift folder we created. It’s also possible to copy over the six silks icons we will probably be utilizing:

  • bullet_green.png
  • bullet_red.png
  • delete.png
  • email_go.png
  • discover.png
  • page_edit.png

I’m going to construction the remaining tutorial on creating the CRUD: create, learn, replace, and delete for 4 of our six fashions. One different will probably be edited by different actions, and the sixth we is not going to be creating the CRUD actions.

Now let’s first create our database, and our tables we be created progressively later. We are actually going to start out coding. Additionally, as a phrase of be aware, I’ll assume that we are going to be working with recordsdata in our admin folder, until I in any other case specify, as most of code be on this folder.


Step 2: Utility Configuration

Each software can have some kind of configuration file, and we’re going to create ours now. Go forward and create a file named config.php and add the next:

1
# admin/config.php 
2
	<?php  
3
	// DB Settings 
4
	outline('DB_SERVER', 'localhost'); 
5
	outline('DB_USER', 'root'); 
6
	outline('DB_PASSWORD', ''); 
7
	outline('DB_NAME', 'nettuts_ns_demo'); 
8
 
9
	outline('FROM_EMAIL', 'no_reply@ohyeahemail.com'); 
10
	outline('FROM_NAME', 'oh yeah e mail!'); 
11
 
12
 
13
	session_start(); 
14
	require_once 'lessons.php'; 
15
	$mini = false; 
16
	$nonav = false; 
17
	error_reporting(0);

So the primary part units up our database variables, so ensure you edit it so it firsts your native configuration. Our subsequent blurb units up some e mail attributes we’ll use later. The final part begins up our session so we are able to entry it, requires our lessons.php file (we’ll create that in only a second), units the defaults for some structure choices, after which units error reporting to 0 to cease annoying warnings. Nonetheless, should you appear to be having hassle, strive commenting out this line.

Now go forward and create our lessons.php file and add in:

1
# admin/lessons.php 
2
	<?php  
3
	// Authentication 
4
	operate validate_user($username, $pw) { 
5
	    if (check_username_and_pw($username, $pw)) { 
6
	        header('Location: index.php'); 
7
	    } else { 
8
	        $_SESSION['error'] = "Login error."; 
9
	        header('Location: login.php'); 
10
	    } 
11
	} 
12
 
13
	operate logged_in() { 
14
	    if ($_SESSION['authorized'] == true) { 
15
	        return true; 
16
	    } else { 
17
	        return false; 
18
	    } 
19
	} 
20
 
21
	operate login_required() { 
22
	    if(logged_in()) { 
23
	        return true; 
24
	    } else { 
25
	        header('Location: login.php'); 
26
	    } 
27
	} 
28
	// mysql  
29
	operate question($sql) { 
30
	  $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
31
 
32
	  $stmt = $hyperlink->put together($sql) or die('error'); 
33
	  $stmt->execute(); 
34
	  $meta = $stmt->result_metadata(); 
35
 
36
	  whereas ($area = $meta->fetch_field()) { 
37
	    $parameters[] = &$row[$field->name]; 
38
	  } 
39
 
40
	  $outcomes = array(); 
41
	  call_user_func_array(array($stmt, 'bind_result'), $parameters); 
42
 
43
	  whereas ($stmt->fetch()) { 
44
	    foreach($row as $key => $val) { 
45
	      $x[$key] = $val; 
46
	    } 
47
	    $outcomes[] = $x; 
48
	  } 
49
 
50
	  return $outcomes; 
51
	  $outcomes->shut(); 
52
	  $hyperlink->shut(); 
53
	} 
54
 
55
	operate count_query($question) { 
56
	  $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
57
	  if($stmt = $hyperlink->put together($question)) { 
58
	    $stmt->execute(); 
59
	    $stmt->bind_result($outcome); 
60
	    $stmt->fetch(); 
61
	    return $outcome; 
62
	    $stmt->shut(); 
63
	  } 
64
	  $hyperlink->shut(); 
65
	} 
66
 
67
	operate check_username_and_pw($u, $pw) { 
68
	  $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
69
 
70
	  $question = "SELECT * FROM customers WHERE username = ? AND password = ? LIMIT 1"; 
71
	  if($stmt = $hyperlink->put together($question)) { 
72
	    $p = md5($pw); 
73
	    $stmt->bind_param('ss', $u, $p); 
74
	    $stmt->execute(); 
75
	    $stmt->bind_result($id, $username, $pw); 
76
	    if($stmt->fetch()) { 
77
	      $_SESSION['authorized'] = true; 
78
	      $_SESSION['username'] = $username; 
79
	      return true; 
80
	    } else { 
81
	      return false; 
82
	    } 
83
	    $stmt->shut(); 
84
	  } 
85
	  $hyperlink->shut(); 
86
	}

That could be a enormous chunk of code, and I will undergo it. Our first operate handles when the consumer posts our login, after which sends the information to our check_username_and_pw operate. Our logged_in operate merely returns whether or not a consumer is logged in. Our login_required operate checks to see if we’re logged in, and if not, sends us to the login web page.

The following operate merely named question() preforms a question on our DB, and was created by Jeffrey Approach. I added the hyperlink creation and shut capabilities to make it even simpler. Our subsequent operate I created particularly so we are able to simply run COUNT SQL queries, and our check_username_and_pw operate checks to see if we are able to discover a consumer with the identical e mail and MD5 hashed password, and in that case, units our session variables.


Step 3: Utility Structure

Our subsequent file we’ll work on is our structure.php file, so go forward and create it. In our head part we merely declare our common XHTML declarations. In the event you discover, we mechanically add the title of the web page to a different string for our title. Then we’ve a stylesheet (go forward and create that too in our media folder). After which we open our physique tag, and test to see if we wish a mini structure, and in that case provides a category. Then we’ve our header, after which test to see if we wish our navigation, and if we do, we present our tabs. I additionally added a manner so as to add a present class for every tab. We additionally then have a logout hyperlink, after which have our container div. On this, we add an h3 tag with our title, after which echo our content material.

1
# admin/structure.php 
2
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
3
	<html xmlns="http://www.w3.org/1999/xhtml" > 
4
	    <head> 
5
	        <meta http-equiv="Content material-Sort" content material="textual content/html; charset=utf-8" /> 
6
 
7
	        <title><?php echo $title; ?> » my publication app</title> 
8
	        <!-- Stylesheets --> 
9
	        <!-- <hyperlink rel="stylesheet" href="https://code.tutsplus.com/media/type.css" kind="textual content/css" media="all" /> --> 
10
	    </head> 
11
	    <physique<?php if ($mini == true) { ?> class="mini"<?php } ?>> 
12
	        <div id="header"> 
13
	            <h1><a href="index.php">my publication app</a></h1> 
14
	        </div> 
15
	        <?php if ($nonav == false) { ?> 
16
	        <div id="nav"> 
17
	            <a href="messages.php"<?php if($tab == 'mess') {?>class="present"<?php } ?>>messages</a> 
18
	            <a href="subscribers.php"<?php if($tab == 'sub') {?>class="present"<?php } ?>>subscribers</a> 
19
	            <a href="newsletters.php"<?php if($tab == 'nl') {?>class="present"<?php } ?>>newsletters</a> 
20
	            <a href="templates.php"<?php if($tab == 'temp') {?>class="present"<?php } ?>>templates</a> 
21
	            <span class="proper"> 
22
	                <a href="logout.php">sign off</a> 
23
	            </span> 
24
	        </div> 
25
	        <?php } ?> 
26
	        <div id="container"> 
27
	            <h3><?php echo $title;?></h3> 
28
	            <?php echo $content material; ?> 
29
	        </div> 
30
	    </physique> 
31
	</html>

Now, we’re going to create our index.php web page simply so we are able to type. Open up index.php and add:

1
# admin/index.php 
2
		<?php 
3
		require_once 'config.php'; 
4
		$title = "Dwelling!"; 
5
		$content material = <<<EOF 
6
		<h3>present stats</h3> 
7
		Our residence web page! 
8
		EOF; 
9
		embrace 'structure.php'; ?>

So on this, we require our config file, arrange our title, after which units up our content material variable, after which final requires our structure file. Once you first open it up it ought to seem like:

9201 9b7137d165e7a44c8cd672ba809f908a9201 9b7137d165e7a44c8cd672ba809f908a9201 9b7137d165e7a44c8cd672ba809f908a

Now open up our type sheet. I like to make use of the 960.gs reset and typography types, compressed in TextMate. So the highest of my CSS file appears like:

1
# admin/media/type.css 
2
	/* reset */ 
3
	html,physique,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,deal with,huge,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,strike,sturdy,sub,sup,tt,var,b,u,i,heart,dl,dt,dd,ol,ul,li,fieldset,type,label,legend,desk,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;define:0;font-size:100%;vertical-align:baseline;background:clear}physique{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}blockquote:earlier than,blockquote:after,q:earlier than,q:after{content material:'';content material:none}:focus{define:0}ins{text-decoration:none}del{text-decoration:line-through}desk{border-collapse:collapse;border-spacing:0} 
4
	/* typography */ 
5
	physique{font:13px/1.5 Helvetica,Arial,'Liberation Sans',FreeSans,sans-serif}a:focus{define:1px dotted invert}hr{border:0 #ccc stable;border-top-width:1px;clear:each;peak:0}h1{font-size:25px}h2{font-size:23px}h3{font-size:21px}h4{font-size:19px}h5{font-size:17px}h6{font-size:15px}ol{list-style:decimal}ul{list-style:sq.}li{margin-left:30px}p,dl,hr,h1,h2,h3,h4,h5,h6,ol,ul,pre,desk,deal with,fieldset{margin:10px 0;}

Let’s first type our most important parts, so add the next types:

1
# admin/media/type.css 
2
	#header {width:85%; margin:0 auto;} 
3
	#header h1 a {text-decoration:none; shade:#000;} 
4
	#container {width:85%; background: #111; margin:5px auto; shade:#fff; padding:10px;}

Now your web page ought to seem like:

9201 87449391999dabb5294eff71731923d19201 87449391999dabb5294eff71731923d19201 87449391999dabb5294eff71731923d1

Now if we type the tabs with a nav background after which a hover background on every of the hyperlinks and it is best to see:

1
# admin/media/type.css 
2
	/* tabs */ 
3
	#nav {margin:0 auto 2px;padding:10px;width:85%; background:#444;} 
4
	#nav a { padding:12px 10px; margin:0; shade:#fff; text-decoration:none; text-align:heart;} 
5
	#nav a.present, #nav a:hover {background:#111;} 
6
	#nav span.proper {float:proper;}
9201 6a29b037141665085d4e53af6d4534ee9201 6a29b037141665085d4e53af6d4534ee9201 6a29b037141665085d4e53af6d4534ee

Now, whereas we’re engaged on the file, go forward and add the next types for our mini structure, type inputs, tables, giant hyperlinks, and our error & success messages.

1
# admin/media/type.css 
2
	physique.mini #header {width:30%; text-align:heart;} 
3
	physique.mini #container {width:30%;} 
4
 
5
	/* type */ 
6
	type enter.textual content {width:95%; font-size:16px;} 
7
	type textarea {width:95%; peak:100%;} 
8
	/* desk */ 
9
	desk {width:98%; text-align:proper; border:rgb(128,128,128); font-size:12px; margin:5px 10px; shade:#000;background:#fff;} 
10
	desk th {background-color: rgb(229, 229, 229); border:1px stable rgb(187, 187, 187); padding:3px 6px; font-weight:regular; shade:#000;} 
11
	desk tr td {border: 1px stable rgb(221, 221, 221); padding:3px 6px;} 
12
	desk tr:hover {background-color: rgb(240, 240, 240);shade:#000;} 
13
	/* a */ 
14
	a.giant {padding: 5px; shade:#000; background:#eee; text-decoration:none; margin:5px;} 
15
	a.giant.proper {float:proper;} 
16
	a.giant:hover, a.giant.present {background:#444; shade:#fff;} 
17
	/* messages */ 
18
	#message {margin: 5px 10px; padding: 4px; show:block;text-align:heart;} 
19
	#message.error {background:#FFEBE8;border: 1px stable #CC0000;shade:#CC0000;} 
20
	#message.success {border:stable 1px #349534; background:#C9FFCA;shade:#008000;}

These are some types that I like to make use of throughout all my tasks. Now that we’ve completed the structure, we’re going to proceed onto authentication.


Step 4: Authentication

We’re going to be working with a quite simple authentication system. Create a login.php and place the next inside:

1
# admin/login.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	if(logged_in()) {header('Location: index.php');} 
5
	$title = "login"; 
6
	$nonav = true; 
7
	$mini = true; 
8
	if($_POST && (!empty($_POST['username']) ) && (!empty($_POST['password']))) { 
9
	    validate_user($_POST['username'], $_POST['password']); 
10
	} 
11
	$error = $_SESSION['error']; 
12
	$content material = <<<EOF 
13
	$error 
14
	<type motion="login.php" technique="submit"> 
15
	    <p> 
16
	        <label for="username">username:</label><br /> 
17
	        <enter kind="textual content" title="username" class="textual content" /> 
18
	    </p> 
19
	    <p> 
20
	        <label for="password">password:</label><br /> 
21
	        <enter kind="password" title="password" class="textual content" /> 
22
	    </p> 
23
	    <p> 
24
	        <enter kind="submit" worth="login" /> 
25
	    </p> 
26
	</type> 
27
	EOF; 
28
	embrace 'structure.php'; ?>

I will clarify every a part of the code. First we require our config file. Subsequent we test to see if we’re logged in, and if we’re, we redirect residence. Subsequent we set the title, and our structure choices. Then we test to see if we’ve a POST and if the POST had a username and password, and in that case, we name the validate_user operate from our lessons file. We subsequent set the variable error to our session errors, after which we arrange our type and output any errors. Now we’re going to create our logout web page, so create logout.php and put the next in it:

1
# admin/logout.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	$_SESSION = array(); 
5
	session_destroy(); 
6
	header('Location: login.php'); 
7
	?>

We once more require our config file, set our session to an empty array, then destroy our session and redirect to our login web page. Now that you’ve finished all this, your login web page ought to seem like:

9201 e8b39f45282c429856f258326068e8fb9201 e8b39f45282c429856f258326068e8fb9201 e8b39f45282c429856f258326068e8fb

We’re additionally going to create a consumer document (and our desk) in order that we are able to add within the authentication logic and you’ll view the pages with the code up forward. To create a consumer with the username of admin and a password of secret. So as to add this, run this SQL:

1
CREATE TABLE `customers` ( 
2
	   `id` int(10) AUTO_INCREMENT, 
3
	   `username` varchar(50), 
4
	   `password` varchar(32), 
5
	   PRIMARY KEY (`id`) 
6
	) ENGINE=MyISAM DEFAULT CHARSET utf8; 
7
 
8
	INSERT INTO `customers` (`id`, `username`, `password`) VALUES  
9
	('1', 'admin', '5ebe2294ecd0e0f08eab7690d2a6ee69');

Step 5: Newsletters

I engineered this software to be very versatile. I wished you (the consumer) to have the ability to create and handle as many newsletters as you need. So, first, we have to create our database desk. Right here is the SQL code from the export on my demo software:

1
 
2
	CREATE TABLE `newsletters` ( 
3
	   `id` int(10) AUTO_INCREMENT, 
4
	   `title` varchar(50), 
5
	   `description` varchar(255), 
6
	   `seen` varchar(10), 
7
	   PRIMARY KEY (`id`) 
8
	) ENGINE=MyISAM DEFAULT CHARSET utf8;

So now that we’ve our newsletters desk, we’re going to create the pages for every motion. Create 4 recordsdata named: newsletters.php, newsletters_delete.php, newsletters_edit.php, and newsletters_new.php. First open up newsletters.php:

1
# admin/newsletters.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$title = "newsletters"; 
6
	$newsletters = question("SELECT * FROM newsletters ORDER BY id ASC"); 
7
	$tab = 'nl'; 
8
	$desk = ""; 
9
	foreach($newsletters as $row) { 
10
	    $dlink = '<a href="https://code.tutsplus.com/newsletters_delete.php?id=".$row['id'].'" onclick="return verify('Are you positive you wish to delete this text?');" title="delete"><img src="https://code.tutsplus.com/media/photographs/delete.png" alt="delete"/></a>'; 
11
	    $elink = '<a href="https://code.tutsplus.com/newsletters_edit.php?id=".$row['id'].'" title="edit" ><img src="https://code.tutsplus.com/media/photographs/page_edit.png" alt="edit"/></a>'; 
12
	    if($row['visible'] == "1") {$seen = '<img src="https://code.tutsplus.com/media/photographs/bullet_green.png" />';} else {$seen = '<img src="https://code.tutsplus.com/media/photographs/bullet_red.png" />';} 
13
	    $desk .= "<tr><td>".$row['id']."</td><td>".$row['name']."</td><td>".$row['description']."</td><td>$seen</td><td>".$dlink." ".$elink."</td></tr>n"; 
14
	} 
15
	$message = error_messages(); 
16
	$content material = <<<EOF 
17
	<a href="newsletters_new.php" class="giant">new publication »</a> 
18
	$message 
19
	<desk> 
20
	    <tr> 
21
	        <th></th> 
22
	        <th>title</th> 
23
	        <th>description</th> 
24
	        <th>seen</th> 
25
	        <th></th> 
26
	    </tr> 
27
	    $desk 
28
	</desk> 
29
	EOF; 
30
	embrace 'structure.php'; ?>

So this file has the identical primary really feel of our login web page. We require our config, make sure that we’re logged in, set our title. Subsequent we use our question() operate to carry out a SELECT question to seek out all of our newsletters. We then set the present tab for our structure. After we loop by means of the array returned by our question, and create the the desk structure. Then we name a yet-unknown operate, and create our web page. Earlier than it is possible for you to to view the web page, you’ll need so as to add the next to your lessons.php file to simply deal with our error messages:

1
# admin/lessons.php 
2
	// Render error messages 
3
	operate error_messages() { 
4
	    $message = ''; 
5
	    if($_SESSION['success'] != '') { 
6
	        $message = '<span class="success" id="message">'.$_SESSION['success'].'</span>'; 
7
	        $_SESSION['success'] = ''; 
8
	    } 
9
	    if($_SESSION['error'] != '') { 
10
	        $message = '<span class="error" id="message">'.$_SESSION['error'].'</span>'; 
11
	        $_SESSION['error'] = ''; 
12
	    } 
13
	    return $message; 
14
	}

Whilst you most likely is not going to have any knowledge, when you’ve got just a few information it’s going to seem like: (although a bit much less squished)

9201 e698b13fa92f1a8aaff11601d340b89e9201 e698b13fa92f1a8aaff11601d340b89e9201 e698b13fa92f1a8aaff11601d340b89e

Now we’re going to work on our new motion, so open up newsletters_new.php and add the next:

1
# admin/newsletters_new.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$tab = 'nl'; 
6
 
7
	if(isset($_POST['submitted'])) {  
8
	    $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
9
	    $sql = "INSERT INTO NEWSLETTERS (title, description) VALUES ( '".$_POST['name']."' , '".$_POST['description']."' )"; 
10
	    $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
11
	    $stmt->shut; 
12
	    $_SESSION['success'] = "Added publication.";  
13
	    header('Location: newsletters.php'); 
14
	} 
15
	$title = "new publication"; 
16
	$content material = <<<EOF 
17
	<type motion="newsletters_new.php" technique='POST'>  
18
	    <p> 
19
	        <label for="title">Identify:</label><br /> 
20
	        <enter kind='textual content' title='title' class="textual content" />  
21
	    </p> 
22
	    <p> 
23
	        <label for="description">Description:</label> 
24
	        <enter kind="textual content" title="description" class="textual content" />  
25
	    </p> 
26
	    <p> 
27
	        <enter kind='submit' worth='Add Publication' /> 
28
	        <enter kind='hidden' worth='1' title='submitted' />  
29
	    </p> 
30
	</type> 
31
	EOF; 
32
	embrace 'structure.php'; ?>

So I hope you’ve got observed the sample on the high of every of our recordsdata. We first require our config.php file, then make sure that we’re logged in, after which set our present tab, and we then add some further logic for dealing with POSTs after which we set our title, our content material, after which render the web page. The POST part is pretty easy to grasp so I will clarify it shortly.

We first test to see if an merchandise with the title of submitted was despatched. That is the hidden area we’ve after the submit button. Subsequent, we create a hyperlink to our database utilizing the variables from our config file. Subsequent we create our SQL insert question, utilizing our POSTed variables. Subsequent we question (not our operate) the database, and if an error is raised, we present the error returned. Subsequent, we shut the question, then we set our success message, after which redirect to the itemizing web page. Your web page ought to seem like:

9201 63f400a5cf37338da2b87389eebc197c9201 63f400a5cf37338da2b87389eebc197c9201 63f400a5cf37338da2b87389eebc197c

Subsequent we’re going to work on our edit web page and add the next:

1
# admin/newsletters_edit.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$tab = 'nl'; 
6
 
7
	if(isset($_POST['submitted'])) {  
8
	    $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
9
	    if(isset($_POST['visible'])) {$seen = 1;}else{$seen = 0;} 
10
	    $sql = "UPDATE NEWSLETTERS SET title="".$_POST["name']."', description='".$_POST['description']."', seen=".$seen." WHERE id=".$_POST['id'].""; 
11
	    $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
12
	    $stmt->shut; 
13
	    $_SESSION['success'] = "Edited publication.";  
14
	    header('Location: newsletters.php'); 
15
	} 
16
	$title = "edit publication"; 
17
	$id = (int) $_GET['id']; 
18
	$outcomes = question("SELECT * FROM newsletters WHERE id='".$id."' LIMIT 1"); 
19
	$title = $outcomes[0]['name']; 
20
	$description = $outcomes[0]['description']; 
21
	$seen = ($outcomes[0]['visible'] == "1") ? 'checked="checked"' : ''; 
22
	$content material = <<<EOF 
23
	<type motion="newsletters_edit.php" technique='POST'>  
24
	    <p> 
25
	        <label for="title">Identify:</label><br /> 
26
	        <enter kind='textual content' title='title' class="textual content" worth="$title" />  
27
	    </p> 
28
	    <p> 
29
	        <label for="description">Description:</label> 
30
	        <enter kind="textual content" title="description" class="textual content" worth="$description" />  
31
	    </p> 
32
	    <p> 
33
	        <label for="seen">Seen:</label> 
34
	        <enter kind="checkbox" title="seen" worth="true" $seen/> 
35
	    </p> 
36
	    <p> 
37
	        <enter kind='submit' worth='Edit Publication' /> 
38
	        <enter kind='hidden' worth='1' title='submitted' />  
39
	        <enter kind='hidden' worth='$id' title='id' /> 
40
	    </p> 
41
	</type> 
42
	EOF; 
43
	embrace 'structure.php'; ?>

Identical to all of our recordsdata, we begin off with the identical block. After our POST block (which I’ll speak about in a second), we set id to our requested id, ensuring it’s an integer. We then use our question operate to seek out the publication we’re working with, and units just a few variables to the returned outcomes. Chances are you’ll ask why we put a [0] earlier than we requested every worth, and the reason being the question operate returns an array of all of the information, and every document is an array, so we have to entry the primary array in our outcomes variable. The road the place we set the variable seen ifs truly a compressed if/else assertion. the if half is the == 1, then if that’s true, the variable is about to checked, else to nothing. Then we’ve our type.

Our POST block is similar to our new web page, and can at all times begin the identical manner throughout the remainder of our pages. We then test to see if the test field was test, and set a variable right here once more. Then we’ve our UPDATE question, once more run the question, set our success message, after which redirect residence. THis is how the shape appears and the message seen after enhancing:

9201 cd6183547d1e707a431b2c04ff5f2b4a9201 cd6183547d1e707a431b2c04ff5f2b4a9201 cd6183547d1e707a431b2c04ff5f2b4a
9201 2af5d09492e2b678eac0f1ecc6ce8e019201 2af5d09492e2b678eac0f1ecc6ce8e019201 2af5d09492e2b678eac0f1ecc6ce8e01

The final web page for this part is the best, as it’s the delete web page. Open up the file and paste to following:

1
# admin/newsletters_delete.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$id = (int) $_GET['id'];  
6
	$hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
7
	$sql = "DELETE FROM newsletters WHERE id=$id LIMIT 1"; 
8
	$stmt = $hyperlink->question($sql) or die($hyperlink->error); 
9
	if($hyperlink->affected_rows) { 
10
	    $_SESSION['success'] = "Publication deleted."; 
11
	} else { 
12
	    $_SESSION['error'] = 'Nothing deleted.'; 
13
	} 
14
	header('Location: newsletters.php');

On this block we require our config, make sure that we’re logged in, then save the requested id to a variable, create a MySQL connection, setup our SQL question, then execute the question. We subsequent test to see if a row was affected, and units a message appropriately. We then redirect to the newsletters web page. Congrats, you’ve got completed the primary of 4 CRUD sections. Subsequent, we’ll work on the CRUD for our templates.


Step 6: Templates

Our software will even enable a number of templates, all saved within the database. First, lets create our database desk:

1
 
2
	CREATE TABLE `templates` ( 
3
	   `id` int(10) AUTO_INCREMENT, 
4
	   `title` varchar(50), 
5
	   `columns` tinyint(5), 
6
	   `physique` textual content, 
7
	   PRIMARY KEY (`id`) 
8
	) ENGINE=MyISAM DEFAULT CHARSET utf8;

We’ve got an auto-incrementing id column, a reputation column, a columns column to save lots of the variety of columns (the applying solely scales to 2 columns, which needs to be sufficient, however can simply be expanded. This may be used for various sections.), and our physique. Identical to final time, we have to make every of our pages, and we can have a templates.php web page, in addition to templates_new.php, templates_edit.php, templates_delete.php, and templates_preview.php. We’re first going to work on our templates.php file, so open it up and paste:

1
# admin/templates.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$title = "templates"; 
6
	$tab = 'temp'; 
7
	$templates = question("SELECT id,title,columns FROM templates ORDER BY id ASC"); 
8
	$desk = ""; 
9
	foreach($templates as $row) { 
10
	    $plink = '<a href="" onClick="window.open('templates_preview.php?id='.$row['id'].'',width=800,peak=600)" title="preview"><img src="https://code.tutsplus.com/media/photographs/discover.png" alt="preview"/></a>'; 
11
	    $dlink = '<a href="https://code.tutsplus.com/templates_delete.php?id=".$row['id'].'" onclick="return verify('Are you positive you wish to delete this template?');" title="delete"><img src="https://code.tutsplus.com/media/photographs/delete.png" alt="delete"/></a>'; 
12
	    $elink = '<a href="https://code.tutsplus.com/templates_edit.php?id=".$row['id'].'" title="edit"><img src="https://code.tutsplus.com/media/photographs/page_edit.png" alt="edit"/></a>'; 
13
	    $desk .= "<tr><td>".$row['id']."</td><td>".$row['name']."</td><td>".$row['columns']."</td><td>".$plink." ".$dlink." ".$elink."</td></tr>n"; 
14
	} 
15
	$message = error_messages(); 
16
	$content material = <<<EOF 
17
	<a href="templates_new.php" class="giant">new template »</a> 
18
	$message 
19
	<desk> 
20
	    <tr> 
21
	        <th></th> 
22
	        <th>title</th> 
23
	        <th>columns</th> 
24
	        <th></th> 
25
	    </tr> 
26
	    $desk 
27
	</desk> 
28
	EOF; 
29
	embrace 'structure.php'; ?>

Once more we begin with the fundamentals. We then preform a question to seek out all of our templates. We then loop by means of every array in templates and we create a desk. We then get our error (and success) messages, after which our content material. Your web page ought to look one thing like:

9201 cdb4c11f72ed29ceb6882c6a4f8b21f69201 cdb4c11f72ed29ceb6882c6a4f8b21f69201 cdb4c11f72ed29ceb6882c6a4f8b21f6

Now, shifting on to our our new web page, paste the next:

1
# admin/templates_new.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$tab = 'temp'; 
6
	if(isset($_POST['submitted'])) {  
7
	    $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
8
	    $sql = "INSERT INTO templates (title, columns, physique) VALUES ( '".$_POST['name']."' , ".$_POST['columns'].", '".mysql_real_escape_string($_POST['body'])."' )"; 
9
	    $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
10
	    $stmt->shut; 
11
	    $_SESSION['success'] = "Added template.";  
12
	    header('Location: templates.php'); 
13
	} 
14
	$title = "new template"; 
15
	$content material = <<<EOF 
16
	<type motion="templates_new.php" technique='POST'>  
17
	    <p> 
18
	        <label for="title">Identify:</label><br /> 
19
	        <enter kind='textual content' title='title' class="textual content" />  
20
	    </p> 
21
	    <p> 
22
	        <label for="columns">Columns</label> 
23
	        <choose title="columns"> 
24
	            <choice worth="1">Single Column Structure</choice> 
25
	            <choice worth="2">Two Column Structure</choice> 
26
	        </choose> 
27
	    </p> 
28
	    <p> 
29
	        <label for="description">Physique: (uncooked html)</label><br /> 
30
	        Use %content material% for a single column structure, %leftcol% and %rightcol% for a two column structure.<br /> 
31
	        <textarea title="physique" rows="35"></textarea>  
32
	    </p> 
33
	    <p> 
34
	        <enter kind='submit' worth='Add Template' /> 
35
	        <enter kind='hidden' worth='1' title='submitted' />  
36
	    </p> 
37
	</type> 
38
	EOF; 
39
	embrace 'structure.php'; ?>

So, once more, we’ve our similar header. Our POST once more creates a MySQL connection, then we create our question, and utilizing mysql_real_escape_string to permit any characters into the document, after which we execute our question, set our success message, and redirect to our templates itemizing. In the event you take a look at our type, I additionally ask for variables to be inserted for our content material, and I’ll present you ways this comes into play later after we match a message with a template. Your web page ought to seem like:

9201 45858a757d6c33bf415ce88e160a4d339201 45858a757d6c33bf415ce88e160a4d339201 45858a757d6c33bf415ce88e160a4d33

Subsequent we’re going to work on our edit web page. In case you have observed, a lot of this code is copy and paste throughout the entire similar actions, so make it straightforward on your self.

1
# admin/templates/edit.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$tab = 'temp'; 
6
	if(isset($_POST['submitted'])) {  
7
	    $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
8
	    $sql = "UPDATE templates SET title="".$_POST["name']."', physique='".mysql_real_escape_string($_POST['body'])."', columns=".$_POST['columns']." WHERE id=".$_POST['id'].""; 
9
	    $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
10
	    $stmt->shut; 
11
	    $_SESSION['success'] = "Edited template.";  
12
	    header('Location: templates.php'); 
13
	} 
14
	$title = "edit template"; 
15
	$id = (int) $_GET['id']; 
16
	$outcomes = question("SELECT * FROM templates WHERE id='".$id."' LIMIT 1"); 
17
	$title = $outcomes[0]['name']; 
18
	$templatedata = stripslashes(htmlspecialchars($outcomes[0]['body'])); 
19
	$content material = <<<EOF 
20
	<type motion="templates_edit.php" technique='POST'>  
21
	    <p> 
22
	        <label for="title">Identify:</label><br /> 
23
	        <enter kind='textual content' title='title' class="textual content" worth="$title"/>  
24
	    </p> 
25
	    <p> 
26
	        <label for="columns">Columns</label> 
27
	        <choose title="columns"> 
28
	            <choice worth="1">Single Column Structure</choice> 
29
	            <choice worth="2">Two Column Structure</choice> 
30
	        </choose> 
31
	    </p> 
32
	    <p> 
33
	        <label for="physique">Physique: (uncooked html)</label><br /> 
34
	        Use %content material% for a single column structure, %leftcol% and %rightcol% for a two column structure.<br /> 
35
	        <textarea title="physique" rows="35">$templatedata</textarea>  
36
	    </p> 
37
	    <p> 
38
	        <enter kind='submit' worth='Edit Template' /> 
39
	        <enter kind='hidden' worth='1' title='submitted' />  
40
	        <enter kind='hidden' worth='$id' title='id' /> 
41
	    </p> 
42
	</type> 
43
	EOF; 
44
	embrace 'structure.php'; ?>

We begin with the identical intro, then our POST block, our title, then our requested id. After, we try to discover the template we’re working with, then units three variables in order that we are able to inset them into our content material block. We additionally convert the entire tags we saved to HTML characters so all the pieces will show. When our POST block, you’ll discover we create our hyperlink, then our question and once more use mysql_real_escape_string to save lots of all the pieces, execute our question, after which set our message, and redirect to our templates checklist. Your edit web page (with a pattern document) ought to seem like:

9201 e4e75325e65964a8bf79d06fe4399d609201 e4e75325e65964a8bf79d06fe4399d609201 e4e75325e65964a8bf79d06fe4399d60

Now we’ll create one other delete web page, so open up our delete web page and paste in:

1
# admin/templates_delete.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$id = (int) $_GET['id'];  
6
	$hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
7
	$sql = "DELETE FROM templates WHERE id=$id LIMIT 1"; 
8
	$stmt = $hyperlink->question($sql) or die($hyperlink->error); 
9
	if($hyperlink->affected_rows) { 
10
	    $_SESSION['success'] = "Template deleted."; 
11
	} else { 
12
	    $_SESSION['error'] = 'Nothing deleted.'; 
13
	} 
14
	header('Location: templates.php');

I hope you’ve got picked up the sample right here, this can be a quite simple web page. Now we’re going to work on an additional web page that isn’t a part of the CRUD spectrum; we’re going to create a preview web page. The binoculars within the motion half on the desk is the hyperlink for each (in a brand new window). So open up our preview web page. The web page could be very easy, we discover our template and echo the information, after which append a javascript shut button. The code appears like:

1
# admin/templates_preview.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$id = (int) $_GET['id']; 
6
	$knowledge = question("SELECT physique FROM templates WHERE id=$id LIMIT 1"); 
7
	$template = $knowledge[0]['body']; 
8
	?> 
9
	<?php echo $template; ?> 
10
	<heart><button kind="button" onclick="self.shut();">shut window</button></heart>

And an instance preview appears like:

9201 32766a20d53ba9fc481787b6e94090ce9201 32766a20d53ba9fc481787b6e94090ce9201 32766a20d53ba9fc481787b6e94090ce

Now we’ve completed with our Templates, we’re prepared to maneuver onto the subsequent step!


Step 7: Subscribers

So now we’re going to work with our subscribers! We’re going to create two tables. The primary:

1
CREATE TABLE `subscribers` ( 
2
	   `id` tinyint(10) AUTO_INCREMENT, 
3
	   `title` varchar(50), 
4
	   `e mail` varchar(50), 
5
	   PRIMARY KEY (`id`) 
6
	) ENGINE=MyISAM DEFAULT CHARSET utf8;

Refers to every subscriber, and the second:

1
CREATE TABLE `subscriptions` ( 
2
	   `id` tinyint(10) AUTO_INCREMENT, 
3
	   `subscriber_id` tinyint(10), 
4
	   `newsletter_id` tinyint(10), 
5
	   PRIMARY KEY (`id`) 
6
	) ENGINE=MyISAM DEFAULT CHARSET utf8;

Creates a desk for our many-to-many relationship with our newsletters. A subscriber can have a number of subscription to newsletters, to allow them to subscribe to a number of ones, and every publication can have many subscribers. To create essentially the most dynamic answer, we’ve a linking desk.

Let’s first create our recordsdata. The recordsdata we’re going are going to have are subscribers.php, subscribers_delete.php, and subscribers_edit.php. Our create motion will probably be created later for the front-end. First open up subscribers.php and paste in:

1
# admin/subscribers.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$title = "subscribers"; 
6
	$tab = 'sub'; 
7
	$desk = ""; 
8
	$messages = question("SELECT * FROM subscribers ORDER BY id ASC"); 
9
	foreach($messages as $row) { 
10
		$dlink = '<a href="https://code.tutsplus.com/subscribers_delete.php?id=".$row['id'].'" onclick="return verify('Are you positive you wish to delete this subscriber?');" title="delete"><img src="https://code.tutsplus.com/media/photographs/delete.png" alt="delete"/></a>'; 
11
		$elink = '<a href="https://code.tutsplus.com/subscribers_edit.php?id=".$row['id'].'" title="edit"><img src="https://code.tutsplus.com/media/photographs/page_edit.png" alt="edit"/></a>'; 
12
		$desk .= '<tr><td>'.$row['id'].'</td><td>'.$row['name'].'</td><td>'.$row['email'].'</td><td>'.$dlink.' '.$elink.'</td></tr>'; 
13
	} 
14
	$message = error_messages(); 
15
	$content material = <<<EOF 
16
	$message 
17
	<desk> 
18
		<tr> 
19
			<th></th> 
20
			<th>title</th> 
21
			<th>e mail</th> 
22
			<th></th> 
23
		</tr> 
24
		$desk 
25
	</desk> 
26
	EOF; 
27
	embrace 'structure.php'; ?>

We’ve got principally the identical itemizing pages as earlier than, besides this time we will probably be discovering our subscribers. Your web page (with some pattern knowledge) ought to seem like:

9201 d2f09a4fdab9ea10bda49c5461c31c6f9201 d2f09a4fdab9ea10bda49c5461c31c6f9201 d2f09a4fdab9ea10bda49c5461c31c6f

Now we’ll transfer on to our edit web page:

1
# admin/subscribers_edit.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$tab = 'sub'; 
6
 
7
	if(isset($_POST['submitted'])) {  
8
	    $id = (int) $_POST['id']; 
9
	    $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
10
	    $sql = "UPDATE subscribers SET title="".$_POST["name']."', e mail="".$_POST["email']."' WHERE id=$id"; 
11
	    $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
12
	    $stmt->shut; 
13
 
14
	    foreach($_POST['newsletter'] as $n) { 
15
	        if($n['exists'] != '1' && $n['subscribe'] == "true") { // If we wish to subscribe however the document doesnt exist 
16
	            $nlid = $n['nlid']; 
17
	            $sql = "INSERT INTO subscriptions (subscriber_id, newsletter_id) VALUES ('$id', '$nlid')"; 
18
	            $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
19
	            $stmt->shut; 
20
	        } elseif ($n['exists'] == '1' && $n['subscribe'] != "true") {// Else if we had an exits however we wish to unsubscribe 
21
	            $subid = $n['subid']; 
22
	            $sql = "DELETE FROM subscriptions WHERE id=$subid LIMIT 1"; 
23
	            $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
24
	            $stmt->shut; 
25
	        } 
26
	    } 
27
	    $_SESSION['success'] = "Edited subscriber.";  
28
	    header('Location: subscribers.php'); 
29
	} 
30
	$title = "edit publication"; 
31
	$id = (int) $_GET['id']; 
32
 
33
	$subscriber = question("SELECT * FROM subscribers WHERE id='$id'"); 
34
	$title = $subscriber[0]['name']; 
35
	$e mail = $subscriber[0]['email']; 
36
 
37
	$newsletters = question("SELECT * FROM newsletters"); 
38
	$subs = question("SELECT * FROM subscriptions WHERE subscriber_id='".$id."'"); 
39
	$subscriptions = ''; 
40
	foreach($newsletters as $nl) { 
41
	    $s = false; 
42
	    $subid = ''; 
43
	    foreach($subs as $sub) { 
44
	        if($sub['newsletter_id'] == $nl['id']) {$s = true; $subid = $sub['id'];} 
45
	    } 
46
	    $checked = ($s == true) ? 'checked="checked"' : ''; 
47
	    $subscriptions .= ' 
48
	    <enter kind="checkbox" title="publication['.$nl["id"].'][subscribe]" worth="true" '.$checked.'/> 
49
	    <label for="publication['.$nl["id"].']">'.$nl['name'].'</label> 
50
	    <enter kind="hidden" title="publication['.$nl["id"].'][exists]" worth="'.$s.'" /> 
51
	    <enter kind="hidden" title="publication['.$nl["id"].'][nlid]" worth="'.$nl['id'].'" /> 
52
	    <enter kind="hidden" title="publication['.$nl["id"].'][subid]" worth="'.$subid.'" /><br /> 
53
	    '; 
54
 
55
 
56
	} 
57
	$content material = <<<EOF 
58
	<type motion="subscribers_edit.php" technique='POST'>  
59
	    <p> 
60
	        <label for="title">Identify:</label><br /> 
61
	        <enter kind='textual content' title='title' class="textual content" worth="$title" />  
62
	    </p> 
63
	    <p> 
64
	        <label for="e mail">Electronic mail</label><br /> 
65
	        <enter kind="textual content" title="e mail" class="textual content" worth="$e mail" />  
66
	    </p> 
67
	    <p> 
68
	        <sturdy>Newsletters:</sturdy><br /> 
69
	        $subscriptions 
70
	    </p> 
71
	    <p> 
72
	        <enter kind='submit' worth='Edit Subscriber' /> 
73
	        <enter kind='hidden' worth='1' title='submitted' />  
74
	        <enter kind='hidden' worth='$id' title='id' /> 
75
	    </p> 
76
	</type> 
77
	EOF; 
78
	embrace 'structure.php'; ?>

This web page is pretty completely different so I’ll clarify every half. The header is similar we’ve been utilizing. I will skip the POST block and are available again to it. We then proceed the identical code. We subsequent discover our present subscriber. Subsequent we discover all newsletters (this consists of ones that aren’t seen – seen imply seen to the general public) after which the entire subscriber’s subscriptions. We subsequent loop by means of each publication document returned, we subsequent reset some values. Subsequent, we loop by means of each subscription the consumer has, and if the subscription’s newsletter_id is the same as the present publication we’re looping we set $s true, and $subid equal to the subscription id. We then set the variable $checked equal to both checked or nothing relying on whether or not a subscription was discovered for this subscriber and the present publication within the loop. Subsequent we create the checkbox type space, with a variety of hidden fields. First, we’ve the precise checkbox with a reputation that may create an array for every checkbox. We then have our label, and subsequent we output whether or not or not the subscription exists, the newsletter_id after which the subscription_id for when the subscription exists. After which we’ve our regular content material.

Now, if we transfer on to our POST block. We first get the id posted from our hidden area on the backside. We subsequent create our MySQL hyperlink. Subsequent we’ve our first SQL question the place we replace the subscriber document. Subsequent we loop by means of each publication checkbox. The primary conditional assertion checks to see if the POSTed knowledge says we would not have an current subscription, and the consumer needs to subscribe to the publication. To deal with this, we’re going to carry out a SQL INSERT into our subscriptions desk the place our subscriber_id is similar because the user_id we’re enhancing, and newsletter_id equal to the ‘nlid’ worth POSTed by one in all our hidden fields. We then execute that SQL INSERT question. The elseif conditional assertion says that if our subscription exists, however the checkbox was unchecked so we unsubscribe, we have to delete the subscription. We deal with this with a SQL DELETE question. To type our question we set $subid equal to the posted worth for our ‘subid’. We then create our question by deleting the document the place the subscription id equals our variable of $subid. Subsequent we execute the question, set our session success message, after which redirect again to our subscribers web page. Your ultimate edit web page ought to seem like: (full of pattern knowledge)

9201 64f8f3d98a20761e0431c743dd12d7759201 64f8f3d98a20761e0431c743dd12d7759201 64f8f3d98a20761e0431c743dd12d775

We’ve got one final web page to work on for the subscribers a part of the backend: the delete web page. Identical to earlier than, this web page could be very easy:

1
# admin/subscribers_delete.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$id = (int) $_GET['id'];  
6
	$hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
7
	$sql = "DELETE FROM subscribers WHERE id=$id LIMIT 1"; 
8
	$stmt = $hyperlink->question($sql) or die($hyperlink->error); 
9
	if($hyperlink->affected_rows) { 
10
	    $_SESSION['success'] = "Subscriber deleted."; 
11
	} else { 
12
	    $_SESSION['error'] = 'Nothing deleted.'; 
13
	} 
14
	header('Location: subscribers.php');

Step 8: Messages

I’ll let you know upfront, this part has essentially the most pages. We will probably be working with seven now, and creating yet another in Step 10. First, we’re going to create our messages desk with this SQL:

1
CREATE TABLE `messages` ( 
2
	   `id` tinyint(10) AUTO_INCREMENT, 
3
	   `topic` varchar(255), 
4
	   `leftcol` textual content, 
5
	   `rightcol` textual content, 
6
	   `template_id` tinyint(10), 
7
	   PRIMARY KEY (`id`) 
8
	) ENGINE=MyISAM DEFAULT CHARSET utf8;

Subsequent, we’ll create the recordsdata for this step. Creates seven recordsdata, every named messages.php, messages_delete.php, messages_edit.php, messages_new.php, messages_new_step2.php, messages_new_step3.php, and messages_preview.php. Let’s first open up messages.php and make it seem like:

1
# admin/messages.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$title = "messages"; 
6
	$tab = 'mess'; 
7
	$desk = ""; 
8
	$messages = question("SELECT * FROM messages ORDER BY id ASC"); 
9
	foreach($messages as $row) { 
10
	    $slink = '<a href="https://code.tutsplus.com/messages_send.php?id=".$row['id'].'" title="ship message"><img src="https://code.tutsplus.com/media/photographs/email_go.png" alt="ship message"/></a>'; 
11
	    $plink = '<a href="https://code.tutsplus.com/messages_preview.php?id=".$row['id'].'" goal="_new" title="preview"><img src="https://code.tutsplus.com/media/photographs/discover.png" alt="preview"/></a>'; 
12
	    $dlink = '<a href="https://code.tutsplus.com/messages_delete.php?id=".$row['id'].'" onclick="return verify('Are you positive you wish to delete this message?');" title="delete"><img src="https://code.tutsplus.com/media/photographs/delete.png" alt="delete"/></a>'; 
13
	    $elink = '<a href="https://code.tutsplus.com/messages_edit.php?id=".$row['id'].'" title="edit"><img src="https://code.tutsplus.com/media/photographs/page_edit.png" alt="edit"/></a>'; 
14
	    $desk .= '<tr><td>'.$row['id'].'</td><td>'.$row['subject'].'</td><td><a href="" onClick="window.open('templates_preview.php?id='.$row['template_id'].'',width=800,peak=600)" title="preview"><img src="https://code.tutsplus.com/media/photographs/discover.png" alt="preview"/></a></td><td>'.$slink.' '.$plink.' '.$dlink.' '.$elink.'</td></tr>'; 
15
	} 
16
	$message = error_messages(); 
17
	$content material = <<<EOF 
18
	<a href="messages_new.php" class="giant">new message »</a> 
19
	$message 
20
	<desk> 
21
	    <tr> 
22
	        <th></th> 
23
	        <th>topic</th> 
24
	        <th>template</th> 
25
	        <th></th> 
26
	    </tr> 
27
	    $desk 
28
	</desk> 
29
	EOF; 
30
	embrace 'structure.php'; ?>

That is our routine desk, besides we now have 4 ‘further’ hyperlinks now, one to ship the message, one to preview, one to edit, and one to delete. Your web page ought to seem like:

9201 1eb7b7dbe236e5894758a81d7d405cf39201 1eb7b7dbe236e5894758a81d7d405cf39201 1eb7b7dbe236e5894758a81d7d405cf3

Now we’re going to begin work on our new pages. The primary web page is the place all messages begin out, after which you possibly can progress on and enter the precise message on the subsequent web page. The explanation for it is because we first must create the preliminary message within the DB and so we are able to discover details about the template. The step2 web page is principally the edit web page (there are six line variations in accordance with FileMerge). Open up our new file and paste the next:

1
# admin/messages_new.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$tab = 'mess'; 
6
	if(isset($_POST['subject'])) {  
7
	    $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
8
	    $sql = "INSERT INTO messages (topic, template_id) VALUES ( '".$_POST['subject']."' , ".$_POST['template'].")"; 
9
	    $stmt = $hyperlink->question($sql) or die($hyperlink->error);     
10
	    $i = question("SELECT id FROM messages WHERE topic="".$_POST["subject']."' AND template_id=".$_POST['template']." "); 
11
	    $id = $i[0]['id']; 
12
	    $stmt->shut; 
13
	    $_SESSION['success'] = "Added template.";  
14
	    header('Location: messages_new_step2.php?id=' + $id); 
15
	} 
16
	$title = "new message"; 
17
	$templates = question("SELECT id,title,columns FROM templates"); 
18
	$tselect = '<choose title="template">'; 
19
	foreach($templates as $row) { 
20
	    $tselect .= '<choice worth="'.$row['id'].'">'.$row['name'].'</choice>'; 
21
	} 
22
	$tselect .= "</choose>"; 
23
	$content material = <<<EOF 
24
	<type motion="messages_new.php" technique='POST'>  
25
	    <p> 
26
	        <label for="topic">Topic:</label><br /> 
27
	        <enter kind='textual content' title='topic' class="textual content" />  
28
	    </p> 
29
	    <p> 
30
	        <label for="template">Template:</label> 
31
	        $tselect 
32
	    </p> 
33
	    <p> 
34
	        <button onclick="">Proceed »</button> 
35
	    </p> 
36
	</type> 
37
	EOF; 
38
	embrace 'structure.php'; ?>

This web page is similar to what our different new pages seem like, however this one was one change within the POST block. Proper after we carry out the SQL INSERT, we discover the latest insert id. Now this isn’t the proper answer, however I want it to performing one other SQL question to discover a row utilizing unindexed columns. This step ought to seem like:

9201 ec156aa19bde05c747bd9e91e850e1ed9201 ec156aa19bde05c747bd9e91e850e1ed9201 ec156aa19bde05c747bd9e91e850e1ed

We then redirect to step2, so let’s open up the file:

1
# admin/messages_new_step2.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$title = "new message - step 2"; 
6
	$tab = 'mess'; 
7
	$id = (int) $_GET['id']; 
8
 
9
	$mess = question("SELECT * FROM messages WHERE id=$id"); 
10
	$message = $mess[0]; 
11
	$topic = $message['subject']; 
12
 
13
	$templates = question("SELECT id,title,columns FROM templates"); 
14
	$tselect = '<choose title="template">'; 
15
	foreach($templates as $row) { 
16
	    if($message['template_id'] == $row['id']) { 
17
	        $chosen = ' chosen="chosen"'; 
18
	        if($row['columns'] == "1") { 
19
	            $textareas = '<p><label for="physique">Physique: (uncooked html)</label><br /><textarea title="physique" rows="35"></textarea></p>'; 
20
	        } else { 
21
	            $textareas = '<p><label for="leftcol">Left column: (uncooked html)</label><br /><textarea title="leftcol" rows="35"></textarea></p> 
22
	            <p><label for="rightcol">Proper column: (uncooked html)</label><br /><textarea title="rightcol" rows="35"></textarea></p>'; 
23
	        } 
24
 
25
	    } else {$chosen = '';} 
26
	    $tselect .= '<choice worth="'.$row['id'].'"'.$chosen.'>'.$row['name'].'</choice>'; 
27
	} 
28
	$tselect .= '</choose>'; 
29
 
30
	// Verify for a POST 
31
	if(isset($_POST['submitted'])) {  
32
	    $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
33
		$template = question("SELECT columns FROM templates WHERE id=".$message['template_id']); 
34
	    if($template[0]['columns'] == "1") { 
35
	        $physique = mysql_real_escape_string($_POST['body']); 
36
	        $sql = "UPDATE messages SET topic="".$_POST["subject']."', leftcol="$physique" WHERE id=$id"; 
37
	    } else { 
38
	        $leftcol = mysql_real_escape_string($_POST['leftcol']); 
39
	        $rightcol = htmlentities($_POST['rightcol']); 
40
	        $sql = "UPDATE messages SET topic="".$_POST["subject']."', leftcol="$leftcol", rightcol="$rightcol" WHERE id=$id"; 
41
	    } 
42
	    $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
43
	    $stmt->shut; 
44
	    header('Location: messages_new_step3.php?id='.$id); 
45
	} 
46
 
47
	$content material = <<<EOF 
48
	<type motion="messages_new_step2.php?id=$id" technique='POST'>  
49
	    <p> 
50
	        <label for="topic">Topic:</label><br /> 
51
	        <enter kind='textual content' title='topic' class="textual content" worth="$topic"/>  
52
	    </p> 
53
	    <p> 
54
	        <label for="template">Template:</label> 
55
	        $tselect 
56
	    </p> 
57
	    $textareas 
58
	    <p> 
59
	        <enter kind='submit' worth='Proceed »' /> 
60
	        <enter kind='hidden' worth='1' title='submitted' /> 
61
	    </p> 
62
	</type> 
63
	EOF; 
64
	embrace 'structure.php'; ?>

Hopefully you’ve got gotten the gist of all of the pages and perceive the web page above. We’ve got our regular heading. we then set our id from our GET request. Subsequent we discover the message we’re working with, then we discover all of the templates and assemble a drop down. We additionally use this look to outline whether or not we can have one or two textareas. Subsequent we’ve our POST block, which creates the hyperlink, then checks to see if we’re working with one or two columns and creates the suitable SQL question. After that we’ve our type. Your type ought to seem like:

9201 4fb2661d88d6202f7cb4c4113aaf03289201 4fb2661d88d6202f7cb4c4113aaf03289201 4fb2661d88d6202f7cb4c4113aaf0328

Now we’ll proceed onto step 3, so open up the file and paste:

1
# admin/messages_new_step3.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$title = "new message - step 3"; 
6
	$id = (int) $_GET['id']; 
7
	$tab = 'mess'; 
8
 
9
	$mess = question("SELECT * FROM messages WHERE id=$id"); 
10
	$message = $mess[0]; 
11
	$topic = $message['subject']; 
12
 
13
	$content material = <<<EOF 
14
	<a href="messages_preview.php?id=$id" class="giant" goal="_new">preview »</a><br /> 
15
	<p>Do you need to <a href="messages.php" class="giant">return to messages</a> or <a href="messages_send.php?id=$id" class="giant">ship the message</a>?</p> 
16
	EOF; 
17
	embrace 'structure.php'; 
18
	?>

The web page could be very easy and is the top of making a message. It affords us just a few hyperlinks. The primary is a hyperlink to preview the message. The following affords to take us again residence. The third affords to take us to ship the message (Step 10). The web page appears like:

9201 db12a2db0986bf57c0e823f38695344f9201 db12a2db0986bf57c0e823f38695344f9201 db12a2db0986bf57c0e823f38695344f

Now we’re going to proceed on to our edit web page. I cannot clarify it as it’s the similar file as messages_new_step2.php, so you possibly can refer there.

1
# admin/messages_edit.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$title = "edit message"; 
6
	$id = (int) $_GET['id']; 
7
	$tab = 'mess'; 
8
 
9
	$mess = question("SELECT * FROM messages WHERE id=$id"); 
10
	$message = $mess[0]; 
11
	$topic = $message['subject']; 
12
 
13
	$templates = question("SELECT id,title,columns FROM templates"); 
14
	$tselect = '<choose title="template">'; 
15
	foreach($templates as $row) { 
16
	    if($message['template_id'] == $row['id']) { 
17
	        $chosen = ' chosen="chosen"'; 
18
	    } else {$chosen = '';} 
19
	    $tselect .= '<choice worth="'.$row['id'].'"'.$chosen.'>'.$row['name'].'</choice>'; 
20
	} 
21
	$tselect .= '</choose>'; 
22
 
23
	$mid = $message['template_id']; 
24
	$template = question("SELECT id,title,columns FROM templates WHERE id=$mid"); 
25
	if($template[0]['columns'] == "1") { 
26
	    $textareas = '<p><label for="physique">Physique: (uncooked html)</label><br /><textarea title="physique" rows="35">'.$message['leftcol'].'</textarea></p>'; 
27
	} else { 
28
	    $textareas = '<p><label for="leftcol">Left column: (uncooked html)</label><br /><textarea title="leftcol" rows="35">'.$message['leftcol'].'</textarea></p> 
29
	    <p><label for="rightcol">Proper column: (uncooked html)</label><br /><textarea title="rightcol" rows="35">'.$message['rightcol'].'</textarea></p>'; 
30
	} 
31
 
32
	// Verify for a POST 
33
	if(isset($_POST['submitted'])) {  
34
	    $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
35
	    if($template[0]['columns'] == "1") { 
36
	        $physique = mysql_real_escape_string($_POST['body']); 
37
	        $sql = "UPDATE messages SET topic="".$_POST["subject']."', leftcol="$physique" WHERE id=$id"; 
38
	    } else { 
39
	        $leftcol = mysql_real_escape_string($_POST['leftcol']); 
40
	        $rightcol = htmlentities($_POST['rightcol']); 
41
	        $sql = "UPDATE messages SET topic="".$_POST["subject']."', leftcol="$leftcol", rightcol="$rightcol" WHERE id=$id"; 
42
	    } 
43
	    $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
44
	    $stmt->shut; 
45
	    $_SESSION['success'] = "Edited message.";  
46
	    header('Location: messages.php'); 
47
	} 
48
 
49
	$content material = <<<EOF 
50
	<type motion="messages_edit.php?id=$id" technique='POST'>  
51
	    <p> 
52
	        <label for="topic">Topic:</label><br /> 
53
	        <enter kind='textual content' title='topic' class="textual content" worth="$topic"/>  
54
	    </p> 
55
	    <p> 
56
	        <label for="template">Template:</label> 
57
	        $tselect 
58
	    </p> 
59
	    $textareas 
60
	    <p> 
61
	        <enter kind='submit' worth='Save »' /> 
62
	        <enter kind='hidden' worth='1' title='submitted' /> 
63
	    </p> 
64
	</type> 
65
	EOF; 
66
	embrace 'structure.php'; ?>

The web page will look nearly similar to our step 2, however the textarea can have content material. Now we’ll create the delete web page with:

1
# admin/messages_delete.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$id = (int) $_GET['id'];  
6
	$hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
7
	$sql = "DELETE FROM messages WHERE id=$id LIMIT 1"; 
8
	$stmt = $hyperlink->question($sql) or die($hyperlink->error); 
9
	if($hyperlink->affected_rows) { 
10
	    $_SESSION['success'] = "Message deleted."; 
11
	} else { 
12
	    $_SESSION['error'] = 'Nothing deleted.'; 
13
	} 
14
	header('Location: messages.php'); ?>

That web page must also look acquainted. The ultimate web page we’re going to work on on this step is our preview web page, so open it up and place:

1
# admin/messages_preview.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$id = (int) $_GET['id']; 
6
 
7
	$mess = question("SELECT * FROM messages WHERE id=$id"); 
8
	$message = $mess[0]; 
9
	$topic = $message['subject']; 
10
	$tid = $message['template_id']; 
11
 
12
	$knowledge = question("SELECT physique,columns FROM templates WHERE id=$tid LIMIT 1"); 
13
	$template = $knowledge[0]['body']; 
14
 
15
	if($knowledge[0]['columns'] == "1") { 
16
	    $leftcol = $message['leftcol']; 
17
	    $physique = str_replace('%content material%', $leftcol, $template); 
18
	} else { 
19
	    $leftcol = $message['leftcol']; 
20
	    $rightcol = $message['rightcol']; 
21
	    $b = str_replace('%leftcol%', $leftcol, $template); 
22
	    $physique = str_replace('%rightcol%', $rightcol, $b); 
23
	} 
24
	?> 
25
	<?php echo $physique; ?> 
26
	<button kind="button" onclick="self.shut();">shut window</button>

This file is considerably completely different than you’ve got seen, so I will stroll you thru it. First have have our regular heading. Subsequent we discover the present message we’re working with, and set just a few variables to the outcomes. Subsequent we discover the template we’re working with and set a variable equal to the physique. Subsequent, we’ve a conditional assertion that checks to see the variety of columns the template has. If it has we use the PHP operate str_replace to interchange the %content material% tag we’ve with our precise content material. In any other case, we first carry out a str_replace for the left column, after which on the results of that we carry out str_replace once more for the appropriate column. Now we’re able to proceed onto the front-end.


Step 9: The Entrance-Finish

We’ve got lastly reached the front-end! For this step and this step solely, I’ll assume the recordsdata we’re working with are within the root of the venture (so not the admin folder, the one containing it). We’re going to be working with 4 recordsdata right here, so go forward and create index.php, preferences.php, subscribe.php and a mode.css file. First open up our index.php file and paste:

1
# index.php 
2
	<?php 
3
	require_once 'admin/config.php'; 
4
	$newsletters = question("SELECT * FROM newsletters WHERE seen=1"); 
5
	$subscriptions = ''; 
6
	foreach($newsletters as $nl) { 
7
	    $subscriptions .= ' 
8
	    <enter kind="checkbox" title="publication['.$nl["id"].'][subscribe]" worth="true" '.$checked.'/> 
9
	    <label for="publication['.$nl["id"].']">'.$nl['name'].'</label> 
10
	    <enter kind="hidden" title="publication['.$nl["id"].'][nlid]" worth="'.$nl['id'].'" /><br /> 
11
	    '.$nl["description"].'<br /> 
12
	    '; 
13
	} 
14
	?> 
15
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
16
	<html xmlns="http://www.w3.org/1999/xhtml" > 
17
	    <head> 
18
	        <meta http-equiv="Content material-Sort" content material="textual content/html; charset=utf-8" /> 
19
 
20
	        <title>my newsletters</title> 
21
	        <!-- Stylesheets --> 
22
	        <hyperlink rel="stylesheet" href="type.css" kind="textual content/css" media="all" /> 
23
	    </head> 
24
	    <physique> 
25
	        <div id="header"> 
26
	            <h1>my newsletters</h1> 
27
	        </div> 
28
	        <div id="container"> 
29
	            <h3>Subscribe to our newsletters!</h3> 
30
	            <type motion="subscribe.php" technique="POST"> 
31
	                <p> 
32
	                    <label for="title">Identify:</label><br /> 
33
	                    <enter kind='textual content' title='title' class="textual content" />  
34
	                </p> 
35
	                <p> 
36
	                    <label for="e mail">Electronic mail</label><br /> 
37
	                    <enter kind="textual content" title="e mail" class="textual content" />  
38
	                </p> 
39
	                <p> 
40
	                    <sturdy>Newsletters:</sturdy><br /> 
41
	                    <?php echo $subscriptions; ?> 
42
	                </p> 
43
	                <p> 
44
	                    <enter kind='submit' worth='Subscribe »' /> 
45
	                    <enter kind='hidden' worth='1' title='submitted' />  
46
	                </p> 
47
	            </type> 
48
	        </div> 
49
	    </physique> 
50
	</html>

I will clarify the web page first after which we’ll get to the image so-far and the web page styling. Within the PHP part on the high we require our config.php file (now within the admin listing), then discover all of our publicly seen newsletters and create a test field array. You’ll discover that we aren’t dealing with the POSTed knowledge right here, and I selected to try this in our subscribe.php, and we’ll get to that, however first let’s type the web page. The web page ought to presently seem like:

9201 366b8bb07a1483688ea8bf2dd560ce44

First I added the 960.gs reset file like I did in our different stylesheet. Then I added the three following types to make the design seem like:

1
# type.css 
2
	#header, #container {width:65%;margin:0 auto; padding:0.7%;} 
3
	#container {background:#ccc;} 
4
	type enter.textual content {width:95%; font-size:16px;} 
5
	#message.success {border:stable 1px #349534; background:#C9FFCA;shade:#008000;}
9201 44145cce1e439fb76db28caac4758cd09201 44145cce1e439fb76db28caac4758cd09201 44145cce1e439fb76db28caac4758cd0

So now that we’ve a clear and easy web page, we’re going to proceed on and work on our subscribe.php file. Go forward and open the file and paste:

1
# subscribe.php 
2
	<?php 
3
	require_once 'admin/config.php'; 
4
 
5
	if(isset($_POST['submitted'])) {  
6
	    $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
7
	    $title = $_POST['name']; 
8
	    $e mail = $_POST['email']; 
9
 
10
	    $sql = "INSERT INTO subscribers (title, e mail) VALUES ('$title', '$e mail')"; 
11
	    $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
12
	    $stmt->shut; 
13
 
14
	    $sql = "SELECT id FROM subscribers WHERE title="$title" AND e mail="$e mail" LIMIT 1"; 
15
	    $subscriber = question($sql); 
16
	    $id = $subscriber[0]['id']; 
17
 
18
	    foreach($_POST['newsletter'] as $n) { 
19
	        if($n['subscribe'] == "true") { // If we wish to subscribe however the document doesnt exist 
20
	            $nlid = $n['nlid']; 
21
	            $sql = "INSERT INTO subscriptions (subscriber_id, newsletter_id) VALUES ('$id', '$nlid')"; 
22
	            $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
23
	            $stmt->shut; 
24
	        }  
25
	    } 
26
	} else {header('Location: index.php');} 
27
	?> 
28
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
29
	<html xmlns="http://www.w3.org/1999/xhtml" > 
30
	    <head> 
31
	        <meta http-equiv="Content material-Sort" content material="textual content/html; charset=utf-8" /> 
32
 
33
	        <title>my newsletters</title> 
34
	        <!-- Stylesheets --> 
35
	        <hyperlink rel="stylesheet" href="type.css" kind="textual content/css" media="all" /> 
36
	    </head> 
37
	    <physique> 
38
	        <div id="header"> 
39
	            <h1>my newsletters</h1> 
40
	        </div> 
41
	        <div id="container"> 
42
	            <h3>Thanks for subscribing!</h3> 
43
	        </div> 
44
	    </physique> 
45
	</html>

This web page could be very very similar to our edit subscribers web page, however no DELETE SQL queries occur right here. We merely test to ensure we’ve all POSTed knowledge. We then set just a few variables to our POSTed knowledge, after which create and carry out a SQL INSERT question so as to add the particular person to our subscribers desk. After which we carry out a SQL question to seek out that simply created subscriber (insert_id was not working this time for me). We then loop by means of the entire POSTed newsletters and test to see if we wish to subscribe to them, and carry out SQL INSERTs when wanted. If all goes to plan, you see a pleasant display screen just like the one beneath:

9201 5a1b9e0c4a887f50a76861c88f5a05859201 5a1b9e0c4a887f50a76861c88f5a05859201 5a1b9e0c4a887f50a76861c88f5a0585

We’ve got on final web page right here to work on, and that’s the preferences.php file. That is the place a consumer can edit their e mail subscription. I’m going to separate the web page in two. First we’ve our PHP block:

1
# preferences.php 
2
	<?php 
3
	require_once 'admin/config.php'; 
4
 
5
	if(isset($_POST['submitted'])) {  
6
	    $id = (int) $_POST['id']; 
7
	    $hyperlink = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was an issue connecting to the database.'); 
8
	    $sql = "UPDATE subscribers SET title="".$_POST["name']."', e mail="".$_POST["email']."' WHERE id=$id"; 
9
	    $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
10
	    $stmt->shut; 
11
 
12
	    foreach($_POST['newsletter'] as $n) { 
13
	        if($n['exists'] != '1' && $n['subscribe'] == "true") { // If we wish to subscribe however the document doesnt exist 
14
	            $nlid = $n['nlid']; 
15
	            $sql = "INSERT INTO subscriptions (subscriber_id, newsletter_id) VALUES ('$id', '$nlid')"; 
16
	            $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
17
	            $stmt->shut; 
18
	        } elseif ($n['exists'] == '1' && $n['subscribe'] != "true") {// Else if we had an exits however we wish to unsubscribe 
19
	            $subid = $n['subid']; 
20
	            $sql = "DELETE FROM subscriptions WHERE id=$subid LIMIT 1"; 
21
	            $stmt = $hyperlink->question($sql) or die($hyperlink->error); 
22
	            $stmt->shut; 
23
	        } 
24
	    } 
25
	    $_SESSION['success'] = "Preferences saved.";  
26
	} 
27
 
28
	if(isset($_GET['email'])) {$e mail = $_GET['email']; $show = 'type';} else {$show = 'discover';} 
29
 
30
	$subscriber = question("SELECT * FROM subscribers WHERE e mail="$e mail""); 
31
	if($subscriber || $show == 'discover') { 
32
	    $id = $subscriber[0]['id']; 
33
	    $title = $subscriber[0]['name']; 
34
	    $e mail = $subscriber[0]['email']; 
35
	} else {header('Location: index.php');} 
36
 
37
	$newsletters = question("SELECT * FROM newsletters WHERE seen=1"); 
38
	$subs = question("SELECT * FROM subscriptions WHERE subscriber_id='".$id."'"); 
39
	$subscriptions = ''; 
40
	foreach($newsletters as $nl) { 
41
	    $s = false; 
42
	    $subid = ''; 
43
	    foreach($subs as $sub) { 
44
	        if($sub['newsletter_id'] == $nl['id']) {$s = true; $subid = $sub['id'];} 
45
	    } 
46
	    $checked = ($s == true) ? 'checked="checked"' : ''; 
47
	    $subscriptions .= ' 
48
	    <enter kind="checkbox" title="publication['.$nl["id"].'][subscribe]" worth="true" '.$checked.'/> 
49
	    <label for="publication['.$nl["id"].']">'.$nl['name'].'</label> 
50
	    <enter kind="hidden" title="publication['.$nl["id"].'][exists]" worth="'.$s.'" /> 
51
	    <enter kind="hidden" title="publication['.$nl["id"].'][nlid]" worth="'.$nl['id'].'" /> 
52
	    <enter kind="hidden" title="publication['.$nl["id"].'][subid]" worth="'.$subid.'" /><br /> 
53
	    '; 
54
	}  
55
	$message = error_messages(); 
56
	?>

On this block, so much is happening. First, we embrace our config file. Subsequent, we test for a POST, and if we’ve one, we replace our database. This portion is copied precisely from our subscribers_edit.php file so you possibly can look there for a bit extra clarification. Subsequent relying on if we’ve a get request, we set our variable (this variable is used within the HTML part of the web page). We then search for a subscriber with that e mail, and if one exists or we’re displaying the discover portion, we proceed, in any other case we’re redirected residence. Subsequent we discover all of our newsletters, and the entire subscriber’s subscriptions, after which create our checkbox type. The HTML portion appears like:

1
# preferences.php 
2
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> 
3
	<html xmlns="http://www.w3.org/1999/xhtml" > 
4
	    <head> 
5
	        <meta http-equiv="Content material-Sort" content material="textual content/html; charset=utf-8" /> 
6
 
7
	        <title>my newsletters - my preferences</title> 
8
	        <!-- Stylesheets --> 
9
	        <hyperlink rel="stylesheet" href="type.css" kind="textual content/css" media="all" /> 
10
	    </head> 
11
	    <physique> 
12
	        <div id="header"> 
13
	            <h1>my newsletters</h1> 
14
	        </div> 
15
	        <div id="container"> 
16
	            <h3>my preferences</h3> 
17
	            <?php if($show == 'type') {?> 
18
	            <type motion="preferences.php" technique="POST"> 
19
	                <p> 
20
	                    <label for="title">Identify:</label><br /> 
21
	                    <enter kind='textual content' title='title' class="textual content" worth="<?php echo $title; ?>"/>  
22
	                </p> 
23
	                <p> 
24
	                    <label for="e mail">Electronic mail</label><br /> 
25
	                    <enter kind="textual content" title="e mail" class="textual content" worth="<?php echo $e mail; ?>"/>  
26
	                </p> 
27
	                <p> 
28
	                    <sturdy>Newsletters:</sturdy><br /> 
29
	                    <?php echo $subscriptions; ?> 
30
	                </p> 
31
	                <p> 
32
	                    <enter kind='submit' worth='Save my preferences »' /> 
33
	                    <enter kind='hidden' worth='1' title='submitted' />  
34
	                    <enter kind='hidden' worth='<?php echo $id; ?>' title='id' /> 
35
	                </p> 
36
	            </type> 
37
	            <?php } else { ?> 
38
	            <?php echo $message; ?> 
39
	            <type motion='preferences.php' technique="get"> 
40
	                <p> 
41
	                    <label for="e mail">Electronic mail</label><br /> 
42
	                    <enter kind="textual content" title="e mail" class="textual content" />  
43
	                </p> 
44
	                <p> 
45
	                    <enter kind='submit' worth='Discover »' /> 
46
	                </p> 
47
 
48
	            </type> 
49
	            <?php } ?> 
50
	        </div> 
51
	    </physique> 
52
	</html>

In our HTML block we’ve two types and a few PHP to decide on which one to show. The highest type is the shape the consumer sees if a document within the database has been discovered. The second type is for getting into your e mail and having the system discover it. The second type appears like:

9201 8346c2627e17db0b74959d4e53b06bc49201 8346c2627e17db0b74959d4e53b06bc49201 8346c2627e17db0b74959d4e53b06bc4

And the primary appears like:

9201 96b63c4ec6ea75929bb624eda15f40819201 96b63c4ec6ea75929bb624eda15f40819201 96b63c4ec6ea75929bb624eda15f4081

And the second type after we saved our preferences:

9201 a5ded3f207fc18e48fdc3b6fcfcb9b5e9201 a5ded3f207fc18e48fdc3b6fcfcb9b5e9201 a5ded3f207fc18e48fdc3b6fcfcb9b5e

Now that we’ve completed the front-end, we’ve one final step: sending the emails!


Step 10: Sending Messages

Our final step is to work on the web page to ship our message. We will probably be working within the admin listing, and just one file will probably be created. Go forward and create our messages_send.php file and place the next in it:

1
# admin/messages_send.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$title = "ship message"; 
6
	$id = (int) $_GET['id']; 
7
	$tab = 'mess'; 
8
 
9
	if(isset($_POST['submitted'])) {  
10
	    $question = "SELECT * FROM subscribers WHERE id=0 "; 
11
	    $emails = array(); 
12
	    foreach($_POST['newsletter'] as $n) { 
13
	        if($n['send'] == "true") { 
14
	            $nlid = $n['nlid']; 
15
	            $e = question("SELECT subscriber_id FROM subscriptions WHERE newsletter_id=$nlid"); 
16
	            foreach($e as $s) { 
17
	                $sqlids .= " OR id=".$s['subscriber_id']; 
18
	            } 
19
	            $question .= $sqlids; 
20
	        } 
21
	    } 
22
	    $subscribers = question($question); 
23
	    foreach($subscribers as $sub) { 
24
	        $emails[$sub['email']] = $sub['name']; 
25
	    } 
26
	    $from = array(FROM_EMAIL => FROM_NAME); 
27
	    // BODY RENDERING 
28
	    $mess = question("SELECT * FROM messages WHERE id=$id"); 
29
	    $message = $mess[0]; 
30
	    $topic = $message['subject']; 
31
	    $tid = $message['template_id']; 
32
 
33
	    $knowledge = question("SELECT physique FROM templates WHERE id=$tid LIMIT 1"); 
34
	    $template = $knowledge[0]['body']; 
35
 
36
	    if($message['rightcol'] == '') { 
37
	        $leftcol = $message['leftcol']; 
38
	        $physique = str_replace('%content material%', $leftcol, $template); 
39
	    } else { 
40
	        $leftcol = $message['leftcol']; 
41
	        $rightcol = $message['rightcol']; 
42
	        $b = str_replace('%leftcol%', $leftcol, $template); 
43
	        $physique = str_replace('%rightcol%', $rightcol, $b); 
44
	    } 
45
 
46
	    send_email_to_mass($from, $emails, $physique, $topic) or die('lol'); 
47
	    header('Location: index.php'); 
48
	} 
49
 
50
	$newsletters = question("SELECT * FROM newsletters"); 
51
	foreach($newsletters as $nl) { 
52
	    $nls .= ' 
53
	    <enter kind="hidden" title="publication['.$nl["id"].'][nlid]" worth="'.$nl['id'].'" /> 
54
	    <enter kind="checkbox" title="publication['.$nl["id"].'][send]" worth="true" '.$checked.'/> 
55
	    <label for="publication['.$nl["id"].']">'.$nl['name'].'</label> - '.$nl['description'].'<br /> 
56
	    '; 
57
	} 
58
	$mess = question("SELECT * FROM messages WHERE id=$id"); 
59
	$message = $mess[0]; 
60
	$topic = $message['subject']; 
61
 
62
	$content material = <<<EOF 
63
	<a href="messages_preview.php?id=$id" class="giant" goal="_new">preview »</a><br /> 
64
	<type motion='messages_send.php?id=$id' technique="POST"> 
65
	    <p> 
66
	        Topic: $topic<br /> 
67
	    </p> 
68
	    <p>Ship to:<br /> 
69
	        $nls 
70
	    </p> 
71
	    <p> 
72
	        <enter kind='submit' worth='Ship »' /> 
73
	        <enter kind='hidden' worth='1' title='submitted' /> 
74
	    </p> 
75
	</type> 
76
	EOF; 
77
	embrace 'structure.php'; ?>

The primary half we once more require our config, then make sure that the consumer is logged in, then our title, make sure that our id is an integer, after which set our tab. Subsequent we’ve our difficult submit block. First we arrange our base question, and operating simply that might return 0 information, which is sweet as a result of meaning no customers will probably be ship the publication. Subsequent we loop by means of each publication that we wish to ship to, and discover the entire subscriptions for that publication. We then create a string that will probably be appended to our unique SQL question in order that we are able to discover each subscriber. Now, we run that question and create an array the place the keys are the emails and the title is the worth, and this helps us use names when the consumer appears on the e mail of their mail software, displaying the TO: as their title. We subsequent discover the message we’re working with, and set the topic, message, and template id to variables. We then discover our template and set the physique to a variable. Then we use the identical code from the message preview to interchange the strings contained in the template the the elements of the message. Then we name our yet-to-be-created-function send_email_to_mass after which redirect residence.

Leaving our POST block, we create the identical checkbox checklist of newsletters so the admin can decide which one(s) he needs to ship the message to. Then we’ve a easy type that appears like:

9201 00b2cd5cf9aa59040ad9e4fdd9ddd6b79201 00b2cd5cf9aa59040ad9e4fdd9ddd6b79201 00b2cd5cf9aa59040ad9e4fdd9ddd6b7

Now, open up our lessons.php file and add the next operate:

1
# admin/lessons.php 
2
	// EMAIL 
3
	operate send_email_to_mass($from, $recipients, $physique, $topic) { 
4
	    require_once 'swift/lib/swift_required.php'; //require lib 
5
 
6
	    $transport = Swift_MailTransport::newInstance(); 
7
	    $mailer = Swift_Mailer::newInstance($transport) or die('Error creating mailer.'); 
8
	    $message = Swift_Message::newInstance($topic) 
9
	        ->setFrom($from) 
10
	        ->setTo($recipients) 
11
	        ->setBody($physique, 'textual content/html') or die('error right here.'); 
12
	    $outcome = $mailer->batchSend($message); 
13
 
14
	    return true; 
15
	}

So first, we’ve our operate declaration, and it expects 4 variables to be handed to it, from, recipients, physique, and topic. Subsequent we require the sqift_required.php file of our Swift Mailer Library. Subsequent we create a brand new Mail Transport (this makes use of the PHP mail operate, so it could be sending out of your native machine, for the documentation on the three transport varieties, see the documentation). Subsequent we create a mailer utilizing that transport. Then we create a brand new message from our topic, then set our from, to, and physique. Then we use the batch_send operate so that every recipient solely sees themselves on the e-mail, and nobody else.

There’s one probably draw back of doing it the way in which I’ve, and that’s in case you are sending many messages, the web page could take perpetually to load. An answer to tthis could be operating a Javascript AJAX request to ship each message, however I will not cowl that right here. Now that we’ve completed engaged on sending messages, we’re going to boost the house web page after which we will probably be finished!


Step 11: The Homepage

Once you load the admin index, the web page does not likely do a lot. I wish to have some ‘stats’ on our homepage, and we’ll lastly use the count_query operate. Open up the admin index file and alter it to seem like:

1
# admin/index.php 
2
	<?php 
3
	require_once 'config.php'; 
4
	login_required(); 
5
	$customers = count_query("SELECT COUNT(*) AS num FROM customers"); 
6
	$emails = count_query("SELECT COUNT(*) AS num FROM subscribers"); 
7
	$subs = count_query("SELECT COUNT(*) AS num FROM subscriptions"); 
8
	$nls = count_query("SELECT COUNT(*) AS num FROM newsletters"); 
9
	$mess = count_query("SELECT COUNT(*) AS num FROM messages"); 
10
	$temps = count_query("SELECT COUNT(*) AS num FROM templates"); 
11
	$title = "Dwelling!"; 
12
	$content material = <<<EOF 
13
	<h3>present stats</h3> 
14
	<p>$customers consumer registered</p> 
15
	<p>$emails subscribers</p> 
16
	<p>$subs publication subscriptions</p> 
17
	<p>$nls newsletters</p> 
18
	<p>$mess messages</p> 
19
	<p>$temps templates</p> 
20
	EOF; 
21
	embrace 'structure.php'; ?>

The web page could be very easy. We require our config, make sure that we’re logged in, then we carry out six depend queries, one for every of our tables after which output that. That is what the ultimate web page seem like:

9201 e28572b88b92b40b81bab7a506d8f6aa9201 e28572b88b92b40b81bab7a506d8f6aa9201 e28572b88b92b40b81bab7a506d8f6aa

Conclusion

Congratulations, you’ve got completed! I hope you loved the tutorial and it didn’t confuse you an excessive amount of 🙂


Full Screencast

cc8ac1ecfe8bc536560440192671a00a45fa87ac
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments