Blogging Fusion » Blog Details for My Programming Tutorials

Offering Bloggers a better chance to stand out from the crowd since 2006!




Follow Us


Available Upgrade Detected
If you are the owner of My Programming Tutorials, or someone who enjoys this blog why not upgrade it to a Featured Listing or Permanent Listing?.

UPGRADE

SHARE THIS PAGE ON:
Blog Details
Blog Directory ID: 34105 Get VIP Status?
: Report Blog Listing This is a free listing which requires a link back!
Google Pagerank: 1
Blog Description:

My Programming Tutorials is one stop solution for passionate programmers which provides various tips and tricks on mobile app and web development and google apis.
Blog Added: November 22, 2017 02:13:25 AM
Audience Rating: General Audience
Blog Platform: WordPress
Blog Country: India   India
Blog Stats
Total Visits: 1,082
Blog Rating: 5.00
Add the ReviewMe Button Or SEO Rank to your Blog!
Review My Programming Tutorials at Blogging Fusion Blog Directory
My Blogging Fusion Score

Featured Resources

Example Ad for My Programming Tutorials

This what your My Programming Tutorials Blog Ad will look like to visitors! Of course you will want to use keywords and ad targeting to get the most out of your ad campaign! So purchase an ad space today before there all gone!

https://www.bloggingfusion.com
notice: Total Ad Spaces Available: (2) ad spaces remaining of (2)

Advertise in this blog listing?

Blog specific ad placement
Customize the title link
Place a detailed description
It appears here within the content
Approved within 24 hours!
100% Satisfaction
If not completely satisfied, you'll receive 3 months absolutely free;
No questions asked!
Buy Now!
Alexa Web Ranking: 426,832

Alexa Ranking - My Programming Tutorials
Subscribe to My Programming Tutorials
Subscribe Now!
Dictionaries should be free

In the current society, education is really important and the tendency starts to show up that people are trying to get the best education quality that they can. However, in most of the countries it is impossible to get an education for free. That means that if you want to become successful in the today’s… Read More » The post Dictionaries should be free appeared first on My Programming...

In the current society, education is really important and the tendency starts to show up that people are trying to get the best education quality that they can. However, in most of the countries it is impossible to get an education for free. That means that if you want to become successful in the today’s society, you will have to start paying money all the way from the first years of getting out of the kinder garden.

The thing which has also become popular among those studying at schools and colleges is learning of the foreign languages. That is a thing which is told to help you a lot in the future if you will have an ability to visit a place abroad. However, people say that even if you will not have that opportunity given to you, you will still be able to learn a lot by studying the second or third foreign language. The main argument is the fact that you will be learning about a new culture, while learning the language. You will find out about the new countries and their cultures when learning some words that do not happen to be real in your home country.

So, how does all of this apply to the topic of the text. Well, we can call many various ways of studying the languages, but one of the oldest and yet the best ways that you will find nowadays is the dictionary method. It has been proven that the method where you learn the new words is not that good for those who are just starting to learn the new language. Yet with the learning of the groups of words, and also the single ones later on in the process of studying, you can easily become pretty fluent in the language you are studying. The other great thing about the dictionary method is the fact that if you add it to the other methods, it will make the learning process way easier. Therefore, such an old and not really efficient method can still exist in the current learning variety.

So, why dictionaries should be free in the current society. Well, that is pretty simple. They are the only way which can be used by poor to learn the new languages. Yet, with the price of some advanced dictionaries, the poorer people are left without a chance to learn something a little over the basics. And many services are already trying to provide help with such works. For example, some volunteer programs are giving out dictionaries to the poor and those in need. For students many various programs exist, which help with their languages. For those looking for a job it is a little harder, as they have no time to actually learn something, because of their look for a job. Therefore, such people should try to use the cover letter writing service in order to save their time and do the stuff they actually need, while they can still study the foreign language a little later.

The other great reason for starting a free distribution of dictionaries is the fact that many foreign tourists come into the new countries with them, and they definitely require some help from the locals at most of their period of staying abroad. And the problem is that many of them do not know the local language or at least English, or the locals might not know how to communicate with the strangers. Moreover, many travellers travel around the world with literally no money, meaning that they would not be able to even get the simplest help from the locals. That brings us to the point where we can say that dictionaries are going to be useful for those travelling on a low budget. It will definitely help the tourists to stay informed in the foreign country and have some help from the people who they are going to be surrounded by. Also, that will help a lot with the getting of new friends. Even if you can communicate well with your friends from abroad, using one of the words from their language will definitely boost the morale of the group, and that will help to keep the nice relations between the friends.

The topic of friendship is actually a great reason to make dictionaries free. People, especially the new generations are going to be able to talk to the people from abroad, which is always good for both of those talking, as they are going to learn a lot of new stuff about each other cultures, and at the same time they will be able to communicate on any of the topics of the interests that both people share. Therefore, we can say that by giving out the free knowledge in general, we can easily create new ties with people all around the world. The other reason is the fact that the companies that print can easily make a portion of dictionaries to be given out for free. They will not lose that much money to care about it. Moreover, they can create a new version of a dictionary to be less advanced, and at the same time with the soft cover, which will decrease the price of producing of such a book way lower, and that will definitely boost the PR of that company and rating in the eyes of people.

To sum everything up, we can say that there is no doubt that dictionaries should be made free, and that will not bring anything bad to any of the sides. However, the modern companies are so scared to lose the money that they would never risk making such a PR move, because it requires some money invested into something which might not bring too many people in. Yet, we all know that free dictionaries will give many people a chance to know much more.

The post Dictionaries should be free appeared first on My Programming Tutorials.



Web Notifications Using Laravel and Pusher

Web notification is a particular message that generates from a website, whenever any update or important message is shared on the app. These messages pop up on your desktop or device even when the respective page is not opened on your current browser. These push notifications are a great addition to the traditional email and… Read More » The post Web Notifications Using Laravel and Pusher appeared first on My Programming...

Web notification is a particular message that generates from a website, whenever any update or important message is shared on the app. These messages pop up on your desktop or device even when the respective page is not opened on your current browser.

These push notifications are a great addition to the traditional email and marketing campaigns. As a user is notified with a push notification every time whenever any update is generated and the users just have to click on that to be notified about any update.

Pusher

Pusher is a hosted service that allows web and mobile applications to add real time data to its live functionality. It works as a real time correspondent between the servers and clients. It establishes persistent connections with the clients on HTTP using WebSocket, therefore, whenever your server receives new data, it gets instantly passed on to the respective clients for maintaining live data concurrency.

In order to integrate in all major languages and frameworks, Pusher offers several libraries to achieve the integration, including libraries of PHP, Ruby, Python, Java, .NET, Go and Node for the server, and JavaScript, Objective-C (iOS) and Java (Android) for the client.

Being known as a highly scalable real time solution for apps, Pusher first came to prominence in 2010 and since then it has continued to remain as the top choice for many. The list of its happy customers includes GitHub, MailChimp, CodeShip, The Financial Times, UserVoice, Travis CI and many others.

Pusher Real-time Use Cases

Pusher has a number of common use cases for real-time web technologies including:

  1. Activity Streams
  2. Data Visualisations/Dashboards
  3. Notifications & Signalling
  4. Collaborative Apps
  5. Chat
  6. Multiplayer Games

The simplest use case of Pusher is the real time notifications. Whenever something relevant occurs according to the website user’s journey, it automatically pops up a notification for the event. This is the same functionality we have seen on Twitter, Facebook and in many other social media platforms for years.

Notification can also be seen as a form of signaling, as it does not contains any organized representation in the UI of the application, but still triggers a reaction within an application.

As far as the current social web apps are concerned, it is very common to have interactive real time notifications. We have the examples of Facebook, Twitter and other social networking sites, which support integration of creative built-in notification systems within them. In this regard, Pusher is one of the most used and popular services which helps you incorporate real-time notifications to your apps and helps you make them more lively and interactive.

In this blog, I will demonstrate about how to implement real time notification system using Laravel and Pusher.

Prerequisites

For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:

  • Laravel 5.5
  • Pusher

I have decided to host my Laravel application on PHP MySQL hosting. It has great devstack and is known for its highly secured platform. You can also try out Cloudways for free by signing up for an account

Setup your Pusher Account

After successfully completing Laravel installation, now let’s create a Pusher account to get API key and other necessary credentials.

Web Notifications

Setup Pusher in Laravel application

After completing the signup process, carefully note down all the credentials including API key, secret key and others. Then open SSH command interface and write down the following command:

Web Notifications Laravel

.env
Once the composer finishes its process, you can configure Laravel and Pusher. Open the .env file from the root directory of Laravel app and update its values to the desired ones.

// Get the credentials from your pusher dashboard
PUSHER_APP_ID=XXXXX
PUSHER_APP_KEY=XXXXXXX
PUSHER_APP_SECRET=XXXXXXX

Web Notifications Pusher

Create Notification Event

First of all, you must create an Event class that could broadcast to Pusher from your live Laravel application. Also remember that you can easily eradicate Events from anywhere in the application.

php artisan make:event Notification

The above-mentioned code will create a new Notification class in the app/Events directory. Open the contents of the file and update as shown below:

<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class Notification implements ShouldBroadcast{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $username;
    public $message;

    public function __construct(){
        //your variables
    }

    public function broadcastOn(){
        return ['notification'];
    }
}

In the above-mentioned code, I have created a ShouldBroadcast interface which defines Laravel that the broadcasting of event should be with using whatever driver, which I have configured in the configuration file.

I have also created a constructor which accepts two parameters (username and verb). I have assigned these variables to class properties which also have the same name. Do remember to set the visibility of these properties to public, because they will be ignored if they aren’t set to public.

Lastly, I have set the channel name to broadcast on.

Create Controller

Now let’s create a controller, which will hold notification code logic. Open the SSH command terminal and paste the following command.

.$ php artisan make:controller PusherNotificationController

After successfully creating the controller, paste the following code in controller file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Pusher\Pusher;

class PusherNotificationController extends Controller{

    public function sendNotification(){
        //Remember to change this with your cluster name.
        $options = array(
            'cluster' => 'ap2',
            'encrypted' => true
        );

        //Remember to set your credentials below.
        $pusher = new Pusher(
            'key',
            'secret',
            'app_id', $options
        );

        $message= "Hello Cloudways";

        //Send a message to notify channel with an event name of notify-event
        $pusher->trigger('notification', 'notification-event', $message);
    }
}

It’s time to add Pusher in the controller. You will have to setup cluster and other credentials like secret key, API etc in your controller as well.

Afterwards, you can publish to a channel and can define a specific name for that channel. For this particular tutorial, I have given channel the name of ‘Notification’, and ‘Notification Event’ as the event name. You can also change these names to any other name according to your preference. Do remember to always use the same channel name and event name in your front end clients.

Setup Route

Now I will show you how to add notification route to the web.php file, which I will use to send notifications using Pusher.

//web.php

Route::get('/notification', 'PusherNotificationController@sendNotification');

Create View

Finally after setting up controller and required routes, now let’s move to create view. Working on welcome.blade.php, paste the below following code in your view file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Real-time notifications in Laravel using Pusher</title>

</head>
<body>
    <h1>Real-time notifications using Pusher In Laravel</h1>

    <!-- Incldue Pusher Js Client via CDN -->
    <script src="https://js.pusher.com/4.2/pusher.min.js"></script>
    <!-- Alert whenever a new notification is pusher to our Pusher Channel -->

    <script>
        //Remember to replace key and cluster with your credentials.
        var pusher = new Pusher('key', {
            cluster: 'ap2',
            encrypted: true
        });

        //Also remember to change channel and event name if your's are different.
        var channel = pusher.subscribe('notification');
        channel.bind('notification-event', function(message) {
            alert(message);
        });

    </script>
</body>
</html>

Now, let’s open up a new tab and visit www.yourdomain/notification while having the www.yourdomain.dev/welcome open in another tab and you should see the alert!.

To see the alert, open a new tab and visit www.yourdomain/notification while having the www.yourdomain.dev/welcome open on one tab. It will definitely show the alert and hence it will confirm the process mentioned in the preceding paragraphs.

Summing Up

In this blog, I have demonstrated how to implement real time notifications in a Laravel app using Pusher. Because Pusher allows us to add more live functionality to our apps and helps make it more interactive, popular social apps like Facebook and Twitter have live web notifications system integrated in their platform. Hence, using Pusher, we can also implement the same functionality in our apps and can enhance the real time interaction while using them.

If you still have more questions regarding this blog, or you want to contribute more on this topic, do feel free to share your thoughts and comments in the comments section below.

The post Web Notifications Using Laravel and Pusher appeared first on My Programming Tutorials.



How To Create Infinite Scroll Pagination With PHP And Ajax

In this tutorial, we are going to learn that how to create infinite scroll pagination with PHP and Ajax. All of you probably must have seen this feature in some websites that you can load more content by just scrolling down. It can be possible via AJAX. I hope all of you guys will be familiar with… Read More » The post How To Create Infinite Scroll Pagination With PHP And Ajax appeared first on My Programming...

In this tutorial, we are going to learn that how to create infinite scroll pagination with PHP and Ajax.

All of you probably must have seen this feature in some websites that you can load more content by just scrolling down.

It can be possible via AJAX. I hope all of you guys will be familiar with Ajax, if not please see what actually an AJAX is?

Let me show you some live examples of infinite scroll pagination, as you are a regular user of Facebook & Twitter etc. I bet you noticed that they use this kinda pagination. When you scroll down they load more contents on your timeline.

View Demo

infinite scroll pagination with php and ajax

In my previous article, I have covered the pagination with PHP and MySql, If you have not read it yet, then I suggest you read that article first. Because the pagination part will be done by PHP itself.

Requirements to create infinite scroll pagination with PHP and Ajax

1. GIF Loader

I have used Preloaders in this article. Preloader provides almost all type of animated GIF Loaders. It is necessary to show a loading process while fetching data asynchronously.

2. A jQuery plugin called Inview

Inview is a JQuery Plugin, which is designed to fire an event as soon as the targeted element appears on the user’s viewport.

You must have JQuery installed in your page to work with Inview. The important thing is, it works only with jQuery 1.8 & upwards. To learn more about Inview, visit Github jquery.inview.

Usage of Inview

$('#target_element_id').on('inview', function(event, isInView) {
    if (isInView) {

        // element is now visible in the viewport

    } else {

        // element has gone out of viewport

    }
});

Let’s dig into actual coding

1. HTML part

<div id="response">

    <!-- response(next page's data) will get appended here -->

    <!--we need to populate some initial data-->
    <?php
        $conn=mysqli_connect("localhost","my_user","my_password","my_db");
        // Check connection
        if (mysqli_connect_errno()){
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            die();
        }
        $sql = "SELECT * FROM table LIMIT 5";
        $res_data = mysqli_query($conn,$sql);
        while($row = mysqli_fetch_assoc($res_data)){
            echo '<div>Demo'.$row["id"].'</div>';
        }
        mysqli_close($conn);
    ?>

</div>

<input type="hidden" id="pageno" value="1">
<img id="loader" src="loader.svg">

Lets split above HTML snippet and see what actually they will perform. So here we have Three elements #response, #pageno & #loader.

#response element would be the container for our fetched data. We will use AJAX request to fetch next page’s data and append it in #response element.

#pageno is a kind of page number counter, we are using it to identify that how much pages have loaded. We have set its default value to “1” so that it loads the first page first.

#loader will be placed at the last of the results as you can see it in the HTML snippet. When the user scrolls down, the Ajax function that will bring the data of the next page will get fired as soon as the #loader comes in the viewport.

2. AJAX JQuery Part

var nextPage = parseInt($('#pageno').val())+1;

$.ajax({
    type: 'POST',
    url: 'pagination.php',
    data: {
        pageno: nextPage
    },
    success: function(data){
        $('#response').append(data);
        $('#pageno').val(nextPage);
    }
});

Every time when #loader appears in the browser’s viewport then the above Ajax function gets fired and sends a POST request to the pagination.php file.

We are sending a nextPage number along with the POST request so that the pagination.php file can understand which page to load.

When execution of the Ajax function gets finished then pagination.php file returns next page’s data. We need to append that data in our #response element as you can see in the above snippet.

3. PHP part

$pageno = $_POST['pageno'];

$no_of_records_per_page = 10;
$offset = ($pageno-1) * $no_of_records_per_page;

As you can see from here the PHP pagination part has started, as I have suggested earlier you should read my previous article pagination with PHP and MySQL.

The SQL Query for Pagination

$sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page";

Let’s assemble the PHP pagination codes

We are going to put all the PHP codes in the pagination.php file, so go ahead and create the pagination.php file and put below codes into it.

<?php

    $pageno = $_POST['pageno'];

    $no_of_records_per_page = 10;
    $offset = ($pageno-1) * $no_of_records_per_page;

    $conn=mysqli_connect("localhost","my_user","my_password","my_db");
    // Check connection
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        die();
    }

    $sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page";
    $res_data = mysqli_query($conn,$sql);

    while($row = mysqli_fetch_array($res_data)){

        echo '<div>Demo'.$row["id"].'</div>';

    }

    mysqli_close($conn);

?>

so PHP part has been done here.

Let’s assemble the Html and JQuery codes

<!DOCTYPE html>
<html>
<head>
    <title>Infinite Scroll Demo</title>

    <!-- JQuery CDN -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

    <!-- Inview Js (jquery.inview.js) -->
    <script src="jquery.inview.js"></script>

    <style>
        #response div{
            border: 1px solid lightgrey;
            height: 80px;
            margin-bottom: 5px;
            padding: 50px 0px 0px 0px;
            text-align: center;
        }
        #loader{
            display: block;
            margin: auto;
        }
    </style>
</head>
<body>

    <div id="response">

        <!-- response(next page's data) will get appended here -->

        <!--we need to populate some initial data-->
        <?php
            $conn=mysqli_connect("localhost","my_user","my_password","my_db");
            // Check connection
            if (mysqli_connect_errno()){
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
                die();
            }
            $sql = "SELECT * FROM table LIMIT 5";
            $res_data = mysqli_query($conn,$sql);
            while($row = mysqli_fetch_assoc($res_data)){
                echo '<div>Demo'.$row["id"].'</div>';
            }
            mysqli_close($conn);
        ?>
    </div>

     <input type="hidden" id="pageno" value="1">
     <img id="loader" src="loader.svg">
     <script>
         $(document).ready(function(){
             $('#loader').on('inview', function(event, isInView) {
                 if (isInView) {
                     var nextPage = parseInt($('#pageno').val())+1;
                     $.ajax({
                         type: 'POST',
                         url: 'pagination.php',
                         data: { pageno: nextPage },
                         success: function(data){
                             $('#response').append(data);
                             $('#pageno').val(nextPage);
                         }
                     });
                 }
             });
         });
     </script>
</body>
</html>

That’s all folks!!!, If you find this article helpful, don’t forget to share and subscribe us.

The post How To Create Infinite Scroll Pagination With PHP And Ajax appeared first on My Programming Tutorials.



Create own Cryptocurrency: A Step By Step Guide

In this article, I am going to serve you a detailed information about how to create own Cryptocurrency like Bitcoin and Ethereum. And provide you a step by step guide to set it up on a Live Server as well. What is Cryptocurrency? Cryptocurrency is a kind of digital asset or virtual currency that uses cryptography techniques to secure its… Read More » The post Create own Cryptocurrency: A Step By Step Guide appeared first on My Programming...

In this article, I am going to serve you a detailed information about how to create own Cryptocurrency like Bitcoin and Ethereum. And provide you a step by step guide to set it up on a Live Server as well.

What is Cryptocurrency?

Cryptocurrency is a kind of digital asset or virtual currency that uses cryptography techniques to secure its transactions.

Bitcoin, Litecoin, Ripple & Ethereum etc. are the best cryptocurrencies in the world. These are frequently called altcoins, as they all are alternative currencies.

There is one more name blockchain technology is very popular in cryptocurrencies network.

What is Blockchain?

Blockchain is simply a decentralized ledger that keeps records of all transactions that take place across peer-to-peer network.

All the transaction’s details are stored in multiple blocks, and each blocks are connected with each other so that they create a chain of blocks that’s why it is called Blockchain.

There is a video by Simply Explained – Savjee which let you understand easily what actually a blockchain technology is.

How To Create Own Cryptocurrency?

1. Creating Block-chain

There are plenty of full featured Open Source Blockchain available out there. Even anyone can fork the existing Bitcoin’s or Litecoin’s blockchain from Github as well.

Actually we are also going to use an open source technology for our block-chain. Because developing a block-chain from scratch is obviously a big deal and it would definitely cost you a huge amount of money.

We are going to use Multichain to create our cryptocurrency. Multichain is an open source blockchain platform provider. You can learn more about Multichain at their official website.

So lets get started :-

Downloading & Installing Multichain Blockchain on our Live Server

As we are going to install our block-chain directly on a live server, so access your server using SSH via putty as administrator (root access) and run following commands one by one.


cd /tmp

wget https://www.multichain.com/download/multichain-1.0.4.tar.gz

tar -xvzf multichain-1.0.4.tar.gz

cd multichain-1.0.4

mv multichaind multichain-cli multichain-util /usr/local/bin

Full instructions for installing multichain’s block-chain are given at their official page here.

Great! we have installed multichain on our server, now its time to create a block-chain. To create it run below command.


multichain-util create ourchain

ourchain is our blockchain’s name you can name your chain whatever you want.

2. making changes in chain

Okay! now our blockchain has been created and we just need to start it. But I recommend you to make changes as per your need in chain before starting it, because blockchain doesn’t allow any amendments when  it gets started.

I know you all are wondering what changes can we make in our blockchain? So I’m listing down some of major parameters you should change as per your need. Although you can always check all the parameters provided by multichain at their blockchain parameters page.

So access your server using SSH via putty as administrator and run below command


nano ~/.multichain/ourchain/params.dat

Following are the parameters you need to work on.

  • chain-description
  • chain-is-testnet
  • first-block-reward (this would be your total coins in your cryptocurrency economy)
  • anyone-can-connect (set it to true)
  • anyone-can-send (set it to true)
  • anyone-can-receive (set it to true)

after making all the required changes you just need to save the params.dat file.

3. starting the blockchain

One you have made changes you are ready to go. So access you server as root (administrator) and run below command to start your chain.


multichaind ourchain -daemon

This command would generate your First Block which is called The Genesis Block.

4. Testing our cryptocurrency.

Access server using SSH via putty as administrator and run below command


multichain-cli ourchain

This command let we enter into interactive mode. For checking chain’s information run getinfo command.

In next article we will learn Blockchain’s operations i.e. to create new wallet address, send coins to other wallets etc. Subscribe us and don’t forget to share this article with your friends.

The post Create own Cryptocurrency: A Step By Step Guide appeared first on My Programming Tutorials.



How to use SQL Manager in CodeLobster PHP IDE

Probably, every PHP programmer had to create his own framework or library, and it was necessary to work quickly and do everything practically from scratch. Often we need to test some of our ideas or algorithms and we write code for interacting with databases directly, without using ORM frameworks. In addition, SQL that is used… Read More » The post How to use SQL Manager in CodeLobster PHP IDE appeared first on My Programming...

Probably, every PHP programmer had to create his own framework or library, and it was necessary to work quickly and do everything practically from scratch.

Often we need to test some of our ideas or algorithms and we write code for interacting with databases directly, without using ORM frameworks.

In addition, SQL that is used in various libraries and CMS might not work quite efficiently and slow down the site.

In such cases, you need to open the SQL editor and start optimizing the queries.

We bring to your attention an article in which the SQL-manager built-in in CodeLobster PHP IDE will be considered.

On a simple example, we will learn how to effectively use the SQL editor and how to create and configure database connections.

Creating and configuring a connection to MySQL

Go to the main menu "Tools" -> "MySQL" -> "SQL Manager". In the opened tab on the right information panel we have the opportunity to add a host and database, for this click the "Register Host" button.

Fill in all the required fields in the dialog box that appears, and straight away let’s give the connection an informative name and enter it in the "Connection Alias" field.

Then we must specify the host and port of our MySQL server and the name of the database with which we are planning to work.

SQL Manager in CodeLobster PHP IDE

It remains to enter the correct username and password and click "OK".

It is done, the host and database are registered and we can begin to examine the functionality of the SQL manager.

Working with tables and data using SQL manager

The main advantage of the built-in CodeLobster SQL manager is the ability to perform the full range of operations necessary for quality work with database.

A classic set of such functions is called CRUD (Create, Read, Update, Delete). You can create and modify tables in the visual mode, add and delete records, as well as read and edit any information.

This, of course, will save a lot of time for the developer at the stage of designing a database for his application.

For our example, we need to create a table in which information about useful books will be stored, and then display this data in a conveniently readable form using a PHP script.

In the program window, right-click on the name of database to which we just connected and select "Create Table" from the context menu. Enter the name of the table – "books" and click "OK".

Now the CodeLobster opens the table editor, in this tab click the "New Field" button.

CodeLobster table editor

In the dialog that appears, enter the name of the field &quot;id&quot;, it will be our primary key with the INTEGER data type, so check "Not Null" and "Autoincrement" checkboxes. The "Primary Key" field will be selected automatically – this is what we need, click "OK".

The next column of the table will contain the name of the book, for this you can use the variable length string – VARCHAR.

CodeLobster table editor

The field is called "title", we set the maximum length for it of 100 characters. Also, adding a book without a name does not make sense, so we set the "Not Null" restriction by enabling the corresponding checkbox.

In addition, check the option "Primary Key", and as a result, MySQL will create an index for this column. Thanks to this, for example, queries with the WHERE title = “…” expression will be executed much faster when you will be working with a table containing a large number of records.

Another thing worth paying attention to is the "Collation" field. Since we have to work with strings in utf8 encoding, we specify the utf8_general_ci collation, since in MySQL this value is used by default for the utf8 character set.

Click "OK" to save the changes.

In the same way, we create three more columns: "author" and "image" of type VARCHAR(100) to store the name of the author of the book and the name of the file with the cover photo, and the "description" column of TEXT type for a brief description of the book.

After the structure is created, we need to press the "Compile" button to execute the commands for creating and saving the table in the database.

CodeLobster table editor

In the program the window in which we are working now has one more tab – "Data", here you can view and edit the contents of the current table.

At the moment, it is still empty, so we will continue to work, press "Insert Record" – this is a button with a "+" sign.

To start, you need to double-click on the desired field in the column and enter the data. In this case, the values of strings and numeric fields are entered directly in place, and for text fields a special dialog box is used, that facilitates and simplifies the input of text in the form of several lines.

CodeLobster php editor

You do not need to enter the "id" column, since its value will be generated automatically by MySQL engine.

Also, do not forget that the real data insertion will occur only after clicking the "Post Edit" button. So, let’s review the values of fields and, if everything is correct, click the button with "check" sign.

So, pretty quickly, you can pre-populate the database and add as many rows as you need for your application.

Working with SQL editor in CodeLobster

Our IDE uses two-panel windows to edit SQL queries. At the top of the window we can enter a query, and at the bottom we can immediately see its result.

Right-click on the table name and select "New SQL File".

In the opened window of the editor, we begin to enter the query, now you can use intelligent prompts not only on the SQL syntax, but also on the names of the tables.

CodeLobster php editor

By pressing Ctrl + Space in the process of composing the query, we also get an auto-complete window on the names of the columns in the current table. Of course, in order to these functions work correctly, a connection to the database must be established.

After we have entered the query, we press the "Execute" button and examine the results at the bottom of the window.

It is possible to save the created file in your project with the extension .sql, as well as the regular file with the source code and use it then at any time.

All the benefits of the SQL editor are also useful if you have to insert queries directly into PHP code.

For our example, we need to run a query to retrieve all the entries from the "books" table. In the image below, you can make sure that CodeLobster does an excellent job with the mixed code.

CodeLobster php editor

It is known that in the development process, the programmer is not limited to creating a database and populating tables.

After the database is designed and filled with data, you can transfer it to another host or save it for later use in other projects.

To start the process of exporting or moving the database, you need to right-click on the name of the database or table and select the "Export" item.

The Export Wizard starts, it has many options and therefore is flexible configured. With its help in several steps you can export to one SQL-file the structure or data contained in tables or them all together.

CodeLobster php editor

In the case of working with individual tables, their contents can be saved not only in the form of SQL, but also in CSV or TSV format, that is very convenient.

Now any other application can work with the exported records, for example, they can be easily analyzed and edited in Microsoft Word or OpenOffice.

So, let’s sum up

We have discussed in detail the use of the SQL manager in CodeLobster IDE.

By studying the article, you learned how to connect to the MySQL server, how to create tables, add entries and execute queries in the editor window or from PHP scripts.

And, finally, you can not be afraid of losing data, because you will be able to quickly backup any database or table with the help of the Wizard.

So, now you have got all the necessary tools for the full range of works on designing databases for your projects.

The post How to use SQL Manager in CodeLobster PHP IDE appeared first on My Programming Tutorials.



Generating PDFs with DocRaptor’s HTML-to-PDF Library

Many web applications have a PDF export requirement: invoices, reports, brochures, or eBooks. Generating these PDFs, especially if they’re complex or large, can be really challenging. Fortunately, there’s DocRaptor, which provides an easy-to-use API for converting HTML web pages into PDFs. This is a walkthrough of how to setup and use DocRaptor’s PHP library: Installation… Read More » The post Generating PDFs with DocRaptor’s HTML-to-PDF Library appeared first on My Programming...

convert html to pdf with docraptor php library

Many web applications have a PDF export requirement: invoices, reports, brochures, or eBooks. Generating these PDFs, especially if they’re complex or large, can be really challenging. Fortunately, there’s DocRaptor, which provides an easy-to-use API for converting HTML web pages into PDFs. This is a walkthrough of how to setup and use DocRaptor’s PHP library:

Installation

DocRaptor can be installed via the Composer dependency manager or by downloading the files directly. To use Composer, simply run this on your command line:


composer require docraptor/docrapto

 

Alternatively, download and unzip the latest release into your project directory. Simply include autoload.php to get access to the DocRaptor library:


// docraptor.php
require_once('/path/to/docraptor-php/autoload.php');

 Add Your API Key

Unlimited watermarked test documents can made using the “YOUR_API_KEY_HERE” key. If you’re ready to make non-watermarked documents, you can get your own API key by creating an account.


$configuration = DocRaptor\Configuration::getDefaultConfiguration();
$configuration->setUsername("YOUR_API_KEY_HERE");

Add HTML

To make your PDF, simply set the document content to your HTML:


$docraptor = new DocRaptor\DocApi();
$doc = new DocRaptor\Doc();
$doc->setDocumentContent("<html><body>Your HTML goes here!</body></html>");

 

If you want to use an existing website page, just input the URL like this:


$docraptor = new DocRaptor\DocApi();
$doc = new DocRaptor\Doc();
$doc->setDocumentUrl("http://docraptor.com/samples/ebook.html");

 

Either way you decide to input the HTML, any external assets in your HTML (CSS, JS, images) are required to be accessible to the DocRaptor servers. They must also either have absolute URLs or you can include a baseurl in your document or use the baseurl API option.

Set API Options

Since DocRaptor makes PDFs and Excel files, we need to set the document type:


$doc->setDocumentType("pdf");

 

To create the free watermarked documents, we need to set test to true:


$doc->setTest(true);

 

JavaScript processing can be enabled with this command:


$doc->setJavascript(true);

 

See DocRaptor’s API documentation for the full list of API options. There’s a lot of them, but they aren’t necessary for most projects.

Generate the PDF

That’s all the setup that’s required. Creating the document is just one line of code, but we should wrap it error handling:


try {
    $create_response = $docraptor->createDoc($doc);
} catch (DocRaptor\ApiException $error) {
    echo $error . "\n";
    echo $error->getMessage() . "\n";
    echo $error->getCode() . "\n";
    echo $error->getResponseBody() . "\n";
}

Save the PDF

Once generated, the PDF can be saved to the server.


$file = fopen("/tmp/docraptor-php.pdf", "wb");
fwrite($file, $create_response);
fclose($file);

Or Send it to the Browser

Or if we’re creating the PDF after a user action and we want them to immediately download it, we can send it to the browser without saving it on the server:


header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=example.pdf');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($create_response));
ob_clean();
flush();
echo($create_response);
exit;

Complete Example

Putting it all together, here’s the full code for making a PDF with DocRaptor. As you can see, it’s short and offloads all the CPU intensive work off our server and puts it onto DocRaptor. It also lets us rapidly make PDFs if multiple users request a PDF at once, which is hard to do if we try to use an open source library.


<?php
// docraptor.php
require_once('docraptor-php/autoload.php');
$configuration = DocRaptor\Configuration::getDefaultConfiguration();
$configuration->setUsername("YOUR_API_KEY_HERE");
$docraptor = new DocRaptor\DocApi();
$doc = new DocRaptor\Doc();
$doc->setDocumentContent("<html><body>Hello World</body></html>");
//$doc->setDocumentUrl("http://docraptor.com/examples/invoice.html");
$doc->setDocumentType("pdf"); // DocRaptor also makes Excel files
$doc->setTest(true);
//$doc->setJavascript(true);
try {
    $create_response = $docraptor->createDoc($doc);
    $file = fopen("/tmp/docraptor-php.pdf", "wb");
    fwrite($file, $create_response);
    fclose($file);
    //header('Content-Description: File Transfer');
    //header('Content-Type: application/pdf');
    //header('Content-Disposition: attachment; filename=example.pdf');
    //header('Content-Transfer-Encoding: binary');
    //header('Expires: 0');
    //header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    //header('Pragma: public');
    //header('Content-Length: ' . strlen($create_response));
    //ob_clean();
    //flush();
    //echo($create_response);
    //exit;
} catch (DocRaptor\ApiException $error) {
    echo $error . "\n";
    echo $error->getMessage() . "\n";
    echo $error->getCode() . "\n";
    echo $error->getResponseBody() . "\n";
}

 

Despite PDFs being one of the internet’s most common standards, it’s surprisingly difficult to dynamically create PDFs from a website. There’s three primary tools used to create PDFs:

  • PDF Generators allow you to create PDFs by adding text at pixel location 123×456 and an images at pixel location 456×123. While fast to generate and simple, the code to generate these PDFs is brittle and time consuming to write.
  • Browser-Based libraries use Webkit or Chromium to generate a PDF based on HTML. These are fast to setup, but provide limited PDF functionality and quality. Browsers are simply not optimized from PDF generation.
  • Commercial libraries built from the ground up to turn HTML into PDFs. These engines are designed specifically for PDF generation and provide a level of quality and control than the browser-based libraries cannot.

DocRaptor is based on one of the commercial tools, but they offer affordable pricing and an easy-to-use PHP library.

The post Generating PDFs with DocRaptor’s HTML-to-PDF Library appeared first on My Programming Tutorials.



Subscribe to RSS Feed
Other Related Blogs

Link to Category: Programming Blogs


Or if you prefer use one of our linkware images? Click here