We are going to do a performance test on getting the data from MySQL database using PHP vs getting data from MySQL database using AJAX in Javascript. We have a database named classicmodels and a table named orderDetails.
In both the cases, we are fetching data from MySQL database with the help of PHP. But in 1st case, we load the data directly via PHP. And in 2nd case, we load the data via AJAX. It is basically loading the data PHP vs Javascript.
Following is a code that will get the data from database using PHP:
We have created a table with 5 columns. Then we are making a connection with the MySQL database. Then we are getting all the data from orderDetails table. We are using a while loop to loop through all records and mysqli_fetch_object function will return the next row in each iteration. When we use PHP to get data from the database, we get the following results in performance:
performance test php
Now we use the same database, same table, the same number of records, and the same output. In order to get the data using Javascript, we need to create an HTML tag for the table. No need to run any PHP query, not even connection with the database. Give a unique ID to the tag where you want to display all data, in this case, we want to show the data in the table so we have given an ID to tbody tag. Then we are sending an AJAX (no jQuery needed) to test.php file and when the response is received from that file, then we display that data in tbody tag. The response sent from test.php is JSON string so we have to decode that using Javascript JSON.parse function.
index.php
<table>
<tr>
<th>Order number</th>
<th>Product code</th>
<th>Quantity ordered</th>
<th>Price each</th>
<th>Order line number</th>
</tr>
<tbody id="data"></tbody>
</table>
<script>
var ajax = new XMLHttpRequest();
ajax.open("POST", "test.php", true);
ajax.send();
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
var data = JSON.parse(this.responseText);
console.log(data);
var html = "";
for(var a = 0; a < data.length; a++) {
html += "<tr>";
html += "<td>" + data[a].orderNumber + "</td>";
html += "<td>" + data[a].productCode + "</td>";
html += "<td>" + data[a].quantityOrdered + "</td>";
html += "<td>" + data[a].priceEach + "</td>";
html += "<td>" + data[a].orderLineNumber + "</td>";
html += "</tr>";
}
document.getElementById("data").innerHTML += html;
}
};
</script>
Now we need to create a file that will handle that AJAX request. This code will be almost same as we did in simple PHP, but instead of displaying all data, we are adding all data in an array and sending that array as a JSON string to AJAX response using PHP built-in json_encode() function.
In this tutorial, we are going to teach you how you can show a confirmation dialog before deleting any data using Javascript. Suppose you are displaying a lot of data in tabular form in the admin panel, and you have a delete button at the end of each row. Now when someone clicks on it, you may be submitting a form with POST request or redirecting to a page where that data will be deleted. But what if someone accidentally clicks on any row, or clicks the wrong row? Then that row will be deleted from the database.
Alternative
One alternative thing you can do is to put the deleted data in the trash. That will add extra work on the developer side as well as on the user side. Because you have to create a table where trashed data will be stored, then create another page on the admin panel to display trashed data and also the ability to delete or restore the trashed data. You can see that there are 6 or 7 more functions that you have to write. Moreover, there will be extra work for users too, they also have to delete the trashed data regularly.
A simple approach
A simple approach displays a confirmation dialog when the delete button is clicked. Show simple 2 buttons, “Cancel”, “Delete”. When the delete button is clicked from confirmation dialog, then send the request to delete that data from the database. You may encounter yourself in 2 minor problems in this approach. First is “how can I display a confirmation dialog ?”, you can either display javascript native function confirm() but it may not look good with your website design.
People want a more personal look, whenever you are displaying a dialog box, whether it is alert dialog or confirmation dialog, make sure that it goes with the look and feel of your website design. Or you can use external libraries like “Sweetalert“, so you have to download that library, include in your project, and use their functions. But sometimes you do not have your project flooded with external libraries. You may ask yourself “why to include an external library when I can do it in my design framework ?”
As we know that today almost every website is using Bootstrap and your project will also be using a large portion of the Bootstrap framework. So we are going to use Bootstrap to display a confirmation dialog. In Bootstrap, they are called “modal”.
Bootstrap modal
Bootstrap modal can be created by creating a <div> tag and give it a unique ID, also a class named “modal”. There will be 2 inner nested divs, one with class “modal-dialog” and second having class “modal-content”. Modal content div will have 3 sections:
modal-header
modal-body
modal-footer
What we are going to do is to show heading in modal-header div, and create a form in modal-body div, in this form we will create a hidden input field which will be the unique ID of row which needs to be deleted from database. Set the form action attribute to the page where you will handle to perform the delete action. In modal-footer, we will simply create a submit button which will be linked with that form using form attribute. Make sure the form attribute on submit button will be same as form id attribute.
Now create a delete button (or change if you already have one) such that it has an attribute data-id and its value must be the unique ID of that row. Attach an onclick listener which will be called whenever that button is clicked. In this event, we are calling a function named confirmDelete. You can create this delete button inside your table row where you are displaying all data from the database (typically in while() loop).
Now when the button is clicked, we want to set the value of the hidden input field inside the bootstrap modal form to the id of the selected row. Then we will show the confirmation modal. Create the following function in <script> tag:
function confirmDelete(self) {
var id = self.getAttribute("data-id");
document.getElementById("form-delete-user").id.value = id;
$("#myModal").modal("show");
}
Make sure you have given a name attribute to the hidden input field. It will help you to set the value using Javascript before displaying the confirmation dialog. Also, the name attribute is used at the server-side to get the values. Now you will be asked for confirmation before deleting any data from the database WITHOUT USING ANY EXTERNAL LIBRARY other than Bootstrap.
If you are developing backend in PHP, then you can get this value using $_POST[“id”].
Today, we will learn to calculate the time passed since date in days, hours, minutes and seconds. Either you are receiving values in PHP variable from MySQL database, or you are calling an AJAX request, this tutorial will help you in both situations. We will also display the hours, minutes and seconds in leading zeroes. So you will not see time as “7:9:3” but you will see that as “07:09:03” using leading zeroes. We already uploaded 1 more tutorial on calculating the time remaining. If you want to caclulate the remaining time in future date, you can follow our tutorial on that as well:
Calculate remaining time
Calculate time passed
Basically, we are going to get the difference between future date and current date. Then we will extract the days, hours, minutes and hours from that difference. Difference will be in seconds so we have to apply some math on it. First we assume that you are already receiving the value from your MySQL database in PHP variable. We have set the PHP variable below but you can use your own database value:
<?php
$date = "2020-06-07 23:39:00";
?>
Then we will create a <div> where we will display the time passed and a hidden input field to get the PHP variable value in Javascript.
Then create a Javascript function which will be called once simply when the page loads. And then in a setInterval function which will be called each second, so we will display the time passed in seconds as well. We will get 2 date objects, first will be current date and second will be date in future which we are getting from PHP variable.
Get difference in timestamps
Then we will get the timestamp from both dates in milliseconds using getTime() function. Dividing that by 1000 will convert that in seconds. But we will also get the floating numbers when dividing, we can prevent the floating number by calling toFixed(0) function. Since toFixed() function returns a string which will not be helpful in getting the difference between 2 dates, so we have to convert that in double or float. We can do that by calling Math.abs() function, it will return the absolute value. Then we subtract the future timestamp from current timestamp and save that in a variable diff as difference.
This diff variable is also in seconds, now we have to convert that value into days, hours, minutes and seconds. We know that there are 86400 seconds in each day, so dividing the difference by 86400 will return the number of days remaining. And since dividing also cause floating number, so we can prevent that by calling Math.floor() function. It will round the value to the previous number.
For example, if the value is 23.7 then it will return as 23. Time to get the remaining hours, we know that there are 3600 seconds in each hour, so we will divide that difference by 3600, round the value to floor. And since there are 24 hours in each day, so we have to take the modulus by 24. Taking modulus will divide the value and return the remainder.
Get difference in minutes
To get the minutes, we know that there are 60 seconds in each minute and 60 minutes in each hour. So we divide the difference by 60, round the value by floor, then take the modulus by 60. That will return the number of minutes passed since date. To get the seconds, is the simplest among all.
We know the limit for seconds is 60, so we simply take the modulus of difference by 60 and it will return the seconds. If you want to show the leading zeros i.e. zeroes on left if value is less than 10, then you can also put a condition on days, hours, minutes and seconds. Check if the value is less than 10, then prepend the “0” with value. And finally display that in our <div id=”data”></div>
Make sure to call the function in setInterval to update the value each second.
<script>
function func() {
var dateValue = document.getElementById("date").value;
var currentDate = Math.abs((new Date().getTime() / 1000).toFixed(0));
var futureDate = Math.abs((new Date(dateValue).getTime() / 1000).toFixed(0));
var diff = currentDate - futureDate;
var days = Math.floor(diff / 86400);
var hours = Math.floor(diff / 3600) % 24;
var minutes = Math.floor(diff / 60) % 60;
var seconds = diff % 60;
if (days < 10) {
days = "0" + days;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
document.getElementById("data").innerHTML = days + " days, " + hours + ":" + minutes + ":" + seconds;
}
func();
setInterval(func, 1000);
</script>
Today, we will learn to calculate remaining time till future date in days, hours, minutes and seconds. Either you are receiving values in PHP variable from MySQL database, or you are calling an AJAX request, this tutorial will help you in both situations. We will also display the hours, minutes and seconds in leading zeroes.
So you will not see time as “7:9:3” but you will see that as “07:09:03” using leading zeroes. We already uploaded 1 more tutorial on creating a countdown timer using libraries. If you are comfortable to use third party libraries in your project, you can follow our tutorial on that as well.
Using third party library
Basically, we are going to get the difference between current date and the date in future. Then we will extract the days, hours, minutes and hours from that difference. Difference will be in seconds so we have to apply some math on it. First we assume that you are already receiving the value from your MySQL database in PHP variable. We have set the PHP variable below but you can use your own database value:
<?php
$date = "2020-06-07 23:39:00";
?>
Then we will create a <div> where we will display the remaining time and a hidden input field to get the PHP variable value in Javascript.
Then create a Javascript function which will be called once simply when the page loads. And then in a setInterval function which will be called each second, so we will display the remaining time in seconds as well. We will get 2 date objects, first will be current date and second will be date in future which we are getting from PHP variable.
Then we will get the timestamp from both dates in milliseconds using getTime() function. Dividing that by 1000 will convert that in seconds. But we will also get the floating numbers when dividing, we can prevent the floating number by calling toFixed(0) function.
Convert string to double – Javascript
Since toFixed() function returns a string which will not be helpful in getting the difference between 2 dates, so we have to convert that in double or float. We can do that by calling Math.abs() function, it will return the absolute value. Then we subtract the current timestamp from future timestamp and save that in a variable diff as difference.
This diff variable is also in seconds, now we have to convert that value into days, hours, minutes and seconds. We know that there are 86400 seconds in each day, so dividing the difference by 86400 will return the number of days remaining. And since dividing also cause floating number, so we can prevent that by calling Math.floor() function. It will round the value to the previous number.
For example, if the value is 23.7 then it will return as 23. Time to get the remaining hours, we know that there are 3600 seconds in each hour, so we will divide that difference by 3600, round the value to floor. And since there are 24 hours in each day, so we have to take the modulus by 24. Taking modulus will divide the value and return the remainder.
Get seconds from timestamp – Javascript
To get the minutes, we know that there are 60 seconds in each minute and 60 minutes in each hour. So we divide the difference by 60, round the value by floor, then take the modulus by 60. That will return the number of minutes remaining till date. To get the seconds, is the simplest among all.
We know the limit for seconds is 60, so we simply take the modulus of difference by 60 and it will return the seconds. If you want to show the leading zeros i.e. zeroes on left if value is less than 10, then you can also put a condition on days, hours, minutes and seconds. Check if the value is less than 10, then prepend the “0” with value. And finally display that in our <div id=”data”></div>
Make sure to call the function in setInterval to update the value each second. Following function will calculate the remaining time.
<script>
function func() {
var dateValue = document.getElementById("date").value;
var date = Math.abs((new Date().getTime() / 1000).toFixed(0));
var date2 = Math.abs((new Date(dateValue).getTime() / 1000).toFixed(0));
var diff = date2 - date;
var days = Math.floor(diff / 86400);
var hours = Math.floor(diff / 3600) % 24;
var minutes = Math.floor(diff / 60) % 60;
var seconds = diff % 60;
var daysStr = days;
if (days < 10) {
daysStr = "0" + days;
}
var hoursStr = hours;
if (hours < 10) {
hoursStr = "0" + hours;
}
var minutesStr = minutes;
if (minutes < 10) {
minutesStr = "0" + minutes;
}
var secondsStr = seconds;
if (seconds < 10) {
secondsStr = "0" + seconds;
}
if (days < 0 && hours < 0 && minutes < 0 && seconds < 0) {
daysStr = "00";
hoursStr = "00";
minutesStr = "00";
secondsStr = "00";
console.log("close");
if (typeof interval !== "undefined") {
clearInterval(interval);
}
}
document.getElementById("data").innerHTML = daysStr + " days, " + hoursStr + ":" + minutesStr + ":" + secondsStr;
}
func();
var interval = setInterval(func, 1000);
</script>
That’s how you can calculate the remaining time till date in Javascript.
In this article, we will teach you how you can change the hashed password of a user in PHP.
Before you proceed, make sure you have PHP version 5 or greater than 5 till 5.5.0 (PHP 5 >= 5.5.0) or PHP 7. You can check your server’s PHP version by creating a new PHP file and write the following code in it:
<?php
phpinfo();
?>
This tutorial uses PHP password_hash and password_verify functions that allows you to save passwords in MySQL database as hashed strings, so even if your database gets hacked or someone tries to read it, he will still not be able to find the actual passwords of users. For the sake of simplicity, we are going to use a sample table named “users” in MySQL database and it will have just 4 columns:
ID (int, auto increment primary key)
name (text)
email (text)
password (text)
Create an HTML form
Our form will contain 3 fields:
Current password: to check if user has entered its current password correctly.
New password
Confirm password
Paste the following code in page where you want to allow user to change their password (make sure to change the form action attribute to your desired filename):
When you submit the form above, it will send the data to “index.php” page. If you have written any other filename in “action” attribute, paste the following code in that PHP file:
<?php
// Connect with database
$conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");
// Set user ID, you must be getting it from $_SESSION
$user_id = 1;
// This will be called once form is submitted
if (isset($_POST["change_password"]))
{
// Get all input fields
$current_password = $_POST["current_password"];
$new_password = $_POST["new_password"];
$confirm_password = $_POST["confirm_password"];
// Check if current password is correct
$sql = "SELECT * FROM users WHERE id = '" . $user_id . "'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_object($result);
if (password_verify($current_password, $row->password))
{
// Check if password is same
if ($new_password == $confirm_password)
{
// Change password
$sql = "UPDATE users SET password = '" . password_hash($new_password, PASSWORD_DEFAULT) . "' WHERE id = '" . $user_id . "'";
mysqli_query($conn, $sql);
echo "<div class='alert alert-success'>Password has been changed.</div>";
}
else
{
echo "<div class='alert alert-danger'>Password does not match.</div>";
}
}
else
{
echo "<div class='alert alert-danger'>Password is not correct.</div>";
}
}
?>
That’s how you can change the hashed password of a user in PHP and MySQL.
Learn how to Password protect ZIP files in Mac OS X from here.
In this tutorial, we are going to teach you how you can load the content of div only when user scrolled to that section. For example, you have a lot of dynamic sections in your website, loading them all using PHP is very costly since server has to get a lot of data from database and it will make your website load slower.
Get data using AJAX
Second option was to load all data using AJAX, this will solve the first problem because the website will be loaded instantly and all the sections where dynamic data needs to be displayed will send an AJAX request to get that data and display in relevant section using Javascript.
However, take this example, if your website has 10 sections and users mostly use the first 3 sections. This means that the server is serving 7 extra requests which are not commonly being used by client. It will slowdown the server, possibly crash your website if you have a lot of users. What if we find a way of optimization such that the relevant section will only be loaded when required by user.
How it works
Simply means, request of section will be sent to server only when asked by client to get that data. If user is on first 3 sections, then the ajax will be called only 3 times and server will be serving only 3 requests. Request for section 4 will only be served if user moved or scrolled to that section, otherwise it will not be loaded. It will greatly optimize your website and make it load faster and more responsive.
This tutorial is written in pure Javascript, no jQuery or any other external library has been used. So you can use this tutorial under all Javascript and PHP frameworks.
We have created a sample database called “classicmodels” from where we are going to load the data from 4 tables:
customers
employees
offices
products
The important question here is “How am I going to know when user has scrolled to some div ? And how can I tell the server to get data required in that div ? And how to display it in relevant div ?”. For this, we are going to use Javascript built-in IntersectionObserver object, basically it observes all the nodes in the intersection.
Intersection Observer
Intersection is a visible area in browser, when you open any website, the content which is visible to you is in Intersection. So we are going to add all divs which needs to be loaded dynamically under observation. Once that div intersects, we are going to send a simple AJAX request using Javascript (no jQuery), telling the server what type of data we need and then display the data in that div.
Server side (PHP)
Paste the following code in your server side or back-end PHP file, we have named it “Http.php“. Make sure to change the database credentials.
<?php
// File name = Http.php
// Get data from database
if (isset($_GET["type"]))
{
// Connecting with database
$conn = mysqli_connect("localhost", "root", "", "classicmodels");
// Just for testing, set a delay for 2 seconds
sleep(2);
// Getting all results from relevant table
// you can perform different queries for each div using $_GET['type'] variable
$type = $_GET["type"];
$result = mysqli_query($conn, "SELECT * FROM " . $type);
$data = array();
while ($row = mysqli_fetch_object($result))
{
array_push($data, $row);
}
// Sending response back
// we also need to send the type back
echo json_encode(array(
"data" => $data,
"type" => $type
));
exit();
}
?>
Client side
Paste the following code in your client side or front-end. Make sure to change the IDs of divs as per your project. Also set server file name as per yours at line 13.
<!-- Create divs which needs to be loaded by ajax -->
<div id="customers" class="loaded-by-ajax"></div>
<div id="employees" class="loaded-by-ajax"></div>
<div id="offices" class="loaded-by-ajax"></div>
<div id="products" class="loaded-by-ajax"></div>
<script>
// Create observer
var ajaxObserver = new IntersectionObserver(function (items, self) {
// Loop through all items in visible area
for (var a = 0; a < items.length; a++) {
// Check if div under observation is in visiable area
if (items[a].isIntersecting) {
// Get ID
var id = items[a].target.id;
// Call ajax to get data
var ajax = new XMLHttpRequest();
ajax.open("GET", "Http.php?type=" + id, true);
// Show loading in relevant div before ajax
document.getElementById(id).innerHTML = "Loading..." + id;
// This event will be called for each request change status
ajax.onreadystatechange = function () {
// Response is received when ready state is 4 and status is 200
if (this.readyState == 4 && this.status == 200) {
// Convert JSON string into arrays and objects
var response = JSON.parse(this.responseText);
var data = response.data;
var type = response.type;
var html = "";
// Each div might have different layout
if (type == "customers") {
html += "<h1>Customers</h1>";
// Loop through all items
for (var b = 0; b < data.length; b++) {
html += "<p>" + data[b].customerName + "</p>";
}
} else if (type == "employees") {
html += "<h1>employees</h1>";
// Loop through all items
for (var b = 0; b < data.length; b++) {
html += "<p>" + data[b].firstName + " " + data[b].lastName + "</p>";
}
} else if (type == "offices") {
html += "<h1>offices</h1>";
// Loop through all items
for (var b = 0; b < data.length; b++) {
html += "<p>" + data[b].city + "</p>";
}
} else if (type == "products") {
html += "<h1>products</h1>";
// Loop through all items
for (var b = 0; b < data.length; b++) {
html += "<p>" + data[b].productName + "</p>";
}
}
// Render the relevant div
document.getElementById(type).innerHTML = html;
}
};
// Sending the ajax request
ajax.send();
// Prevent the div from being observed again
self.unobserve(items[a].target);
}
}
});
// Add all loaded-by-ajax divs in observation list
var loadedByAjax = document.getElementsByClassName("loaded-by-ajax");
for (var a = 0; a < loadedByAjax.length; a++) {
ajaxObserver.observe(loadedByAjax[a]);
}
</script>
That’s how you can load content only when scrolled using Javascript’s “IntersectionObserver”.
A newsletter is a printed or electronic report containing news concerning the activities of a business or an organization that is sent to its members, customers, employees or subscribers. Newsletters generally contain one main topic of interest to its recipients. In this article, we will discuss you how can send bulk emails using the PHP Mailer library.
Newsletter
Newsletters in websites are used in the form of E-mails and they are the most common type of emails in email marketing. They often contain news and updates, aiming to keep the audience engaged. At the same time, they are also designed to gently push users towards the conversion.
We are going to create a form that will help users to subscribe to the newsletter on your website and you will be able to send bulk emails to all those users. You can send promotional emails to promote your product or you can mail to them whenever you have a new post or news regarding your business, organization or website.
This will create a form with an input field to type email and a submit button which when clicked will submit the form. We are preventing the default behavior of form submission by attaching an event listener called “onsubmit”. This function will be called when the user hits the submit button. We need to prevent the form from submitting and call our AJAX function to save this email in the MySQL database using PHP. At the end we have a paragraph, it will be used to display a message when the email has successfully been stored in the database.
Send an ajax request
<script type="text/javascript">
function doSubscribe() {
var subscriberEmail = document.getElementById("subscriberEmail").value;
var ajax = new XMLHttpRequest();
ajax.open("POST", "subscribe-newsletter.php", true);
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("subscribe-message").innerHTML = "You have been subscribed to our newsletter.";
}
};
ajax.send("subscriberEmail=" + subscriberEmail);
return false;
}
</script>
Here first we have created a Javascript function and we are returning false from it, this will prevent the form from submitting. We are getting the input field value for email using the input field’s unique ID. Then we have created an AJAX object that can be used to send an asynchronous AJAX request. Next, we are calling open function and setting method to “POST”, the second parameter is the name of the file where data needs to be sent and the third parameter is whether the request is asynchronous.
Asynchronous
All modern browsers support asynchronous, so we are setting this to true. As the request is POST, so we also have to attach headers to this request. For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string — name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=).
Before actually sending the request, we are attaching an event listener which will be called when a response is successfully been received from the server. The request is successful if the readyState is 4 and status has a value of 200. When the request is completed, we are simply displaying a message in the paragraph so the user can know that his email has been added in the subscriber’s list.
Save email in MySQL using PHP
Next, we need to create a PHP file that will store this email in MySQL database. First, create a table in your MySQL database and name it “subscribers”. It will have 1 column as auto-increment primary key whose value be unique for each subscriber and its data type should be an integer. It will also have another column for email whose value will be subscriber’s email and its data type should be text.
Save data in MySQL database
Create a new file named “subscribe-newsletter.php” and paste the following code in it. Make sure to change the database credentials as per your database.
Many PHP developers need to send email from their code. The only PHP function that supports this is mail(). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.
The PHP mail() function usually sends via a local mail server, typically fronted by a Sendmail binary on Linux, BSD, and macOS platforms, however, Windows usually doesn’t include a local mail server; PHPMailer’s integrated SMTP implementation allows email sending on Windows platforms without a local mail server.
Install PHPMailer
Open command prompt (Windows) or Terminal (Mac OS) in your project’s root folder and run the following command:
composer require phpmailer/phpmailer
It will install the PHPMailer library in your project. You will see a folder named “vendor” will be created at the root folder of your project. Open the file from where you want to send emails to all your subscribers. And paste the following code in it:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$conn = mysqli_connect("localhost:8889", "root", "root", "tutorials");
$result = mysqli_query($conn, "SELECT * FROM subscribers");
while ($row = mysqli_fetch_object($result))
{
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'adnan@gmail.com';
$mail->Password = '';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
$mail->setFrom('adnan@gmail.com', 'Adnan');
$mail->addAddress($row->email); // Add a recipient
$mail->addReplyTo('adnan@gmail.com', 'Adnan');
// Content
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo '<p>Message has been sent to ' . $row->email . '</p>';
} catch (Exception $e) {
echo "<p>Message could not be sent. Mailer Error: {$mail->ErrorInfo}</p>";
}
}
Here first we are importing PHPMailer library files. Then we are including our “autoload.php” file, it should be automatically created when the composer command is executed. Then we are connecting with the database and fetching all the subscribers from the table. In each loop iteration, we are creating an object of PHPMailer class. Setting the host as Gmail and username and password as one of our Gmail account’s credentials. You need to enter the correct email and password of one of your Gmail account.
Enable google less secure apps
Make sure to enable “less secure apps” for your corresponding Gmail account. You can do that from this link or by tapping the screenshot below.
Set the port number to “587” it is the default for Gmail. Set your email address from where the email should be sent. And the recipient address which we will be receiving from the database. Then we are setting the subject and body of email, the body of the email can contain HTML content. But you can also specify non-HTML content in “AltBody” if the user switches to simple text format. Or if the user has a slow internet connection. Finally, we send the mail and display a confirmation message that an email has been sent. If there is any error, it will be handled in the catch block. We are also displaying an error message if there is any problem in sending en E-mail.
Apply CSS on form
Although your subscription form design will be different for everyone else as per your website’s existing design. But for the sake of simplicity, we are applying some CSS styles just to make it look a little bit good. First, change your form layout and enclose your input field and submit button inside div tag having class as “container”. We will apply styles based on this class.
Learn how to add dynamic rows in a table tag in HTML and Javascript. And also save the data in MySQL database using PHP.
Introduction
Suppose you are trying to generate an invoice for your customers. You wanted to have a functionality where you will be able to add multiple items in an invoice. A simple table tag will be created from where the user will be able to add multiple items. You have added a button labeled as “Add Item” which when clicked will create a new row to add an item.
Now it might sound easy but technically you have to create rows dynamically. Whenever a user clicks on the “Add Item” button, a new row inside table tag should be created and it must be an array as items can be multiple. Then these arrays should be stored in the database using a loop iteration. Following this tutorial, you will be able to do so.
We will be creating 2 tables, although to explain this tutorial only 1 table would be enough but teaching with 2 will help to understand better when you are working on existing projects. We will have 1 table for storing invoices basic data, for example, customer name, etc, and the second table for storing items in that invoice.
“invoices” table
Our first table name is “invoices” and it will have just 2 fields, unique auto-increment ID and customer name. And the second table will be named “items” and have the product name, quantity, etc and also a foreign key that reference for invoice ID.
To add dynamic rows, we are using a <table> tag that will create a table layout so we will add rows in <tbody> tag. As discussed earlier, all rows will be in an array that needs to be stored in the database, so we will create a <form> tag that will help to do this. We are setting the method to POST as the data might be sensitive and long, and action attribute as current file name, you can change this if you want to send data to a different page.
Customer field
We are creating a simple input field for customer name that will be stored in the “invoices” table, you can place your other fields here. Then we are creating a <table> tag and inside it, we will be displaying the number of items, item name, and item quantity. Make sure to give <tbody> tag a unique ID so we can append new rows in it using Javascript.
Below them, we are creating a button which when clicked will call a Javascript function from where we can add a new row inside that table. And finally, a submit button which when clicked will submit the form and we have to save that data in database.
Now we need to create a function which when clicked will add a new node in the <tbody> tag. We have created a variable for the number of items and we are incrementing it on each click. Whenever this function called we are creating a <tr> tag and adding input fields for name and quantity in <td> tags. Notice the “[]” with the input name attribute, this tells that this field will be an array. Lastly, we are creating a new row using tbody function called insertRow() and appending the <tr> HTML in it.
<script>
var items = 0;
function addItem() {
items++;
var html = "<tr>";
html += "<td>" + items + "</td>";
html += "<td><input type='text' name='itemName[]'></td>";
html += "<td><input type='number' name='itemQuantity[]'></td>";
html += "<td><button type='button' onclick='deleteRow(this);'>Delete</button></td>"
html += "</tr>";
var row = document.getElementById("tbody").insertRow();
row.innerHTML = html;
}
function deleteRow(button) {
items--
button.parentElement.parentElement.remove();
// first parentElement will be td and second will be tr.
}
</script>
Style the table
Now we are going to apply some styles on our table just to make it look a little bit good.
Now we just need to store this data in our database. The following code must be put at the top of your file. Our database name is “tutorials” but it will be different in your case, make sure to change the DB name accordingly. Next, check if the form is submitted, the if block will only run after the user submits the form. Get the customer name and insert that in the “invoices” table, it is rather simple.
Remember we added “invoiceId” as a foreign key in “items” table. So, we have to get the newly inserted AUTO-INCREMENT ID. Then we are looping through all the added items. You can either use the “itemName” input field or “itemQuantity” and insert them in “items” table with same invoice ID.
That’s it, the job is done. At this point, you will be able to select multiple items. And add dynamic rows in table tag and inserting them in the database as well. Complete source file along with SQL exported file which will help you to understand the structure of database.
In this tutorial, we will teach you how you can prevent user from login for 30 seconds after they made 3 failed login attempts. We will be using PHP.
We will be saving a session variable of integer type, which will store the number of failed login attempts. So every time user enter the wrong password, we will increment this session variable. You can put your own condition to authenticate user in login_failed variable. $_SESSION is an built-in PHP array and it will automatically initialize some variable if is already not exists. You do not have to intialize variable “login_attempts”.
<?php
session_start();
if (login_failed)
{
$_SESSION["login_attempts"] += 1;
}
?>
Hide sign in button after 3 failed login attempts
Now, to block the user for 30 seconds after 3 failed attempts and un-block him after 30 seconds, we need to perform the following steps:
At login form submit button, first check if number of failed attempts is 3 or greater than 3.
Then we store current time in separate session variable named “locked”.
And at the top of page, check if the user is locked out.
Taking difference of current time and the time when user was locked out, will give the number of seconds.
Check how many seconds has been passed since user was locked out ?
If 30 seconds are passed, simply remove all the session variables we created.
<?php
session_start();
// At the top of page right after session_start();
if (isset($_SESSION["locked"]))
{
$difference = time() - $_SESSION["locked"];
if ($difference > 30)
{
unset($_SESSION["locked"]);
unset($_SESSION["login_attempts"]);
}
}
// In sign-in form submit button
if ($_SESSION["login_attempts"] > 2)
{
$_SESSION["locked"] = time();
echo "Please wait for 30 seconds";
}
else
{
?>
<button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button>
<?php
}
?>
Conclusion
This technique is very useful to prevent brute force attack. Because hacker may try to guess all possible combination of password and run an automatic script to automatically fill the login form with different passwords. In this case, submit button will be hidden after 3 failed login attempts for 30 seconds. Thus it will break the script.
Also it will be useful to prevent DOS (Denial Of Service) attack, which means hacker may try to automatically send a large number of login requests which may slow down your server. But if the submit button was hidden after 3 requests, then it will also break that script.
That’s how you can prevent user from login for 30 seconds after they made 3 failed login attempts in PHP.
In this tutorial, we are going to implement 2 factor login authentication. 2 factor login authentication means that user will be verified twice before login.
1st factor should be what they know, like password or some security question.
2nd factor will be what they have, like mobile or fingerprint.
Database structure
First create a table where all users data will be stored. You might already have that if you are working on existing project. You need to add a new field “phone” in your existing “users” table because we will be sending SMS to this field value. There should be an option to enable or disable this 2 factor authentication, so a boolean field named “is_tfa_enabled”. Also a pin number which will be sent as SMS.
users
id int(11) NOT NULL AUTO_INCREMENT
email text NOT NULL
password text NOT NULL
phone text NOT NULL
is_tfa_enabled tinyint(1) NOT NULL
pin text NOT NULL
User registration
During registration, we need to add a new field for phone number. Below is a sample registration form with password encryption.
There will be no extra field in login, it will have email/username and password or whatever fields you are using to login. The important thing is, we need to send an SMS if the user has enabled 2-factor authentication. Below is a typical login form:
We will send an SMS using Twilio if user has enabled 2-factor authentication. First you need to include Twilio PHP library in your project using composer. Open terminal in your project root folder and run the following command to install Twilio:
composer require twilio/sdk
Create an account on Twilio from here. After creating account, you will be given a $15 balance to test the API. On your Twilio console dashboard you will find your “account SID” and “auth token”. You will need to place those on below variables accordingly:
And when this form submits, we are simply going to check the entered pin with database and login the user. We also need to empty the pin from database so that it cannot be used again.
<?php
session_start();
if (isset($_POST["enter_pin"]))
{
$pin = $_POST["pin"];
$user_id = $_SESSION["user"]->id;
$conn = mysqli_connect("localhost", "root", "", "tutorials");
$sql = "SELECT * FROM users WHERE id = '$user_id' AND pin = '$pin'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
$sql = "UPDATE users SET pin = '' WHERE id = '$user_id'";
mysqli_query($conn, $sql);
$_SESSION["user"]->is_verified = true;
header("Location: index.php");
}
else
{
echo "Wrong pin";
}
}
?>
Now after verification user will be redirected to “index.php” which is by default the home of every website. You might already have a check to prevent the user from entering this page without login. Just need to change few things,
We are displaying 2 radio buttons and an ability to automatically select the radio based on enable or disability of 2-factor authentication. You can use the same condition on all pages which you want to show to only authenticated users. Now we just need to logout the user. We have created a link with text “Logout” which when clicked will redirect the user to “logout.php” page.
That’s how you can add 2 factor login authentication with a timer on your website. If you want to know how to add “reset password” feature in your website, check our free tutorial here.