Author

Ankit Prajapati

Browsing

Uploading images or files is the functionality that is mostly used in web applications. In most cases, we upload a single image or file like a profile picture, pdf file or anything else. In this tutorial, you will learn How to Upload Multiple Images in PHP step by step. Check our demo.

But when it comes to uploading multiple images or files we need to think some logic and process how to do that. But sometimes you have a requirement to upload multiple images at once.

Generally, in the web application, the file/image is uploaded to the folder of the server and the file name is stored in the database. Later the files are fetched from the folder based on the file name stored in the database.  

In this tutorial, we will implement all these processes, step by step.

  • Create a database table.
  • Create an image/file uploading form.
  • The database connection file.
  • The image uploads the logic script file.
  • Display Images from Database.
  • Complete Code

Create a database table

First, we need to make a database table to store the names of images we will upload. As we know earlier, Images are stored in the folder of the server and the name is saved to database tables.

Create two columns named ID and imgName with ID to be auto-incremented. I hope you know how to create tables in the database.

Create an image/file uploading form

  <form action="upload-script.php" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <div class="row">
               <div class="col-md-4">
                   <div class="form-group">
                       <input type="file" name="imageFile[]" required multiple class="form-control">
                   </div>
               </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <input type="submit" name="uploadImageBtn" id="uploadImageBtn" value="Upload Images" class="btn btn-success">
                    </div>
                </div>
            </div>
        </div>
    </form>

If you see in this <form> tag, I used the action to upload-script.php. This is the logic file to upload multiple images. And name=”imageFile[]”, there are square braces that indicate an array of images.

The database connection file

<?php
$hostName = "localhost"; // host name
$username = "root";  // database username
$password = ""; // database password
$databaseName = "codingbirds"; // database name

$connection = new mysqli($hostName,$username,$password,$databaseName);
if (!$connection) {
    die("Error in database connection". $connection->connect_error);
}
?>

This is the connection file to the database. There are hostname, username, password and database name. You can change accordingly.

The image uploads the logic script file

upload-script.php

<?php
include "config.php";
if (isset($_POST['uploadImageBtn'])) {
    $uploadFolder = 'uploads/';
    foreach ($_FILES['imageFile']['tmp_name'] as $key => $image) {
        $imageTmpName = $_FILES['imageFile']['tmp_name'][$key];
        $imageName = $_FILES['imageFile']['name'][$key];
        $result = move_uploaded_file($imageTmpName,$uploadFolder.$imageName);

        // save to database
        $query = "INSERT INTO bird_multiple_images SET imgName='$imageName' " ;
        $run = $connection->query($query) or die("Error in saving image".$connection->error);
    }
    if ($result) {
        echo '<script>alert("Images uploaded successfully !")</script>';
        echo '<script>window.location.href="index.php";</script>';
    }
}

This code has a foreach loop to upload multiple images and uploads them into a folder named “uploads”. And finally saves the name of the images to the database.

Display Images from Database

This is the code to fetch images from the database and display it in a row-column format.

 <?php
// fetch Images
$i = 1;
include "config.php";
$queryGetImg = "SELECT * FROM bird_multiple_images";
$resultImg = $connection->query($queryGetImg);
if ($resultImg->num_rows > 0 ){
  while ($row = $resultImg->fetch_object()){ ?>
     <div class="col-sm-3">
	<h3>Image <?php echo $i;?></h3>
	<img src="<?php echo 'uploads/'.$row->imgName;?>"/>
    </div>
    <?php $i++;
   }
}
?>

Complete Code for How to Upload Multiple Images

Here is the complete code that includes all the steps told above. I separated the code so that you can understand properly. Now following is the complete code for you.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Upload Multiple Images with PHP</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
</head>
<body>
<div class="jumbotron text-center">
    <h1>Upload Multiple Images with PHP</h1>
    <p>Resize this responsive page to see the effect!</p>
</div>
<div class="container">
    <form action="upload-script.php" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <div class="row">
               <div class="col-md-4">
                   <div class="form-group">
                       <input type="file" name="imageFile[]" required multiple class="form-control">
                   </div>
               </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <input type="submit" name="uploadImageBtn" id="uploadImageBtn" value="Upload Images" class="btn btn-success">
                    </div>
                </div>
            </div>
        </div>
    </form>

    <div class="row">
        <?php
        // fetch Images
        $i = 1;
        include "config.php";
        $queryGetImg = "SELECT * FROM bird_multiple_images";
        $resultImg = $connection->query($queryGetImg);
        if ($resultImg->num_rows > 0 ){
            while ($row = $resultImg->fetch_object()){ ?>
                <div class="col-sm-3">
                    <h3>Image <?php echo $i;?></h3>
                    <img src="<?php echo 'uploads/'.$row->imgName;?>"/>
                </div>
           <?php $i++;
            }
        }
        ?>
    </div>
</div>
</body>
</html>

If you face any errors in coding, then you can comment and I will surely help. And you can download the source code from here.

You can watch the video also on my YouTube channel named KanpurWebD and make sure you subscribe also.

 

Happy Coding 🙂

MVC is the software and web development approach that separates the logic of your application.
MVC stands for Model, View, and Controller, later becomes the design pattern for the majority of the software, web applications and frameworks.

Read more about Easiest Framework on PHP

Model

The model is the core part of MCV software or applications. It is the place where the majority of the logic of the application is built. Like getting the data from the database, applying filters. This is responsible for the data storage, process, and delivery of the data to the user in the front end.
The model connects the database where everything is stored. When a user makes valid requests, then it queries the data from the database based on the requests.

View 

The view is the front part of MVC that is visible to the user, while the model was the logic part.
Suppose a college is an application, you can identify the model, view, and controller as – A-Class in a college is a model, Teacher is a controller and students are views. Views are the objects within the application displayed to the user. Views are the interface like text, buttons, images..etc.It is the place where data is displayed after the request submitted, received and validated.

Controller

As the name is itself defines what’s it. A controller controls the user, how to interact with the application. The controller accepts user requests from interface or front-end. These requests are often in the form of HTTP and call the model.
Model retrieve, process and validate the data before returning to the controller.
After validation, the controller uses an appreciate view or status to show the user.

What is MVC? A simple explanation for beginners & Intermediate-process

Let’s take a real-world example. Suppose you have registered on any website using your email address and password.
Now you have done something and signed out. Now after someday you have any work to be done. For this, you want to login to that website again ( Facebook.. assume).

To login to the website you have to enter your email and password.
After pressing the submit button, you may see a loading, with a message please wait. That’s the View.
But in MVC terms, the controller receives your email and password. Now that controller sends them to model.

Now model validates whether these are valid( checks did you registered with these credentials) or not.
Waiting for a second you will get a message saying invalid email or password if you have entered wrong credentials. Otherwise, you will be redirected to the dashboard/home page if correct.


What is the need for MVC?

MVC separates the logic, design and controller part of the application. It reduces complexity and increases the readability of the coding.

MVC reduces the complexity of software and web applications and makes it easier to maintain.
Suppose you are developing a login system for your application.  So you write everything on a single page. The design part, logic part, and database part also.

After some days you will find your self difficult to understand your own code and think why you have written this particular code. 

That’s why we use the MVC pattern. Almost all the frameworks like Django, Flask in Python, Spring, Hibernate in Java and Laravel, CodeIgniter, CakePHP in PHP, use MVC design pattern.

features

  • easy and frictionless testability. Highly testable, extensible and pluggable framework
  • It offers full control over your HTML as well as your URLs.
  • Leverage existing features provided by JSP, Django, etc.
  • Clear separation of logic: Model, View, Controller. Separation of application tasks viz. business logic, Ul logic, and input logic.
  • URL Routing for SEO Friendly URLs. Powerful URL- mapping for comprehensible and searchable URLs.

I hope you got the concept. See you in the next article like this.
Happy Coding 🙂

Publishing the own website on the internet or making it live is the dream of every fresher. If you want to publish your website for free then you are in the right place.  

Most of us learn new things like coding, development  & new technologies. Creating a website is only the first step in getting online, you will also need to host a website or in simple terms upload the website to the internet.  

How you will do that?  

You will need to purchase domain & hosting. The domain is the name by which you will be able to see your website over the internet. For example, codingbirdsonline.com is the domain name.  

And the second thing required is hosting. Hosting is the place where you will upload your website or your website’s files.

  Purchasing domain & hosting requires money at least 1500 to 2000 INR, not considering from reputed hosting company providers like Godaddy, Siteground, Bigrock, etc. Otherwise, they will charge greater than this amount.  

Don’t worry you don’t need to purchase anything to publish your website.   Where can I host my website for free ??  

The answer is 000webhost  

You may be saying what’s this? The is itself a website provides free hosting, you will not be charged even 0 $. How’s it is possible?   Since it provides free hosting, so you will not get a domain like .com, .in,.org, etc.   You will get a subdomain like username.000webhostapp.com ‘username’ can be changed if it does not exist already.   Ready….?  Ok, follow the steps. You need to create the account. Don’t worry it is free.

Signup

Open the website 000webhost.com. When you will open website and clicking signup you will get something like this

How-to-publish-your-website-for-free-signup
How-to-publish-your-website-for-free-signup

Email Verification

Remember you can not create two accounts by the same email id. After signup, you will get an email asking to verify your email so that your account can be activated. It is like this

How to publish your website for free step-by-step

Members Panel

After email verification, you will be asked that what you are interested in, what you want to create a website or blog like this. Simply skip all you will be redirected to members panel as …

How to publish your website for free-member-panel
How to publish your website for free-member-panel

Create New Site

Now you can see there is a create site button click on you will get a popup asking to enter website name and a password, copy your password somewhere. Your website name will codingbirdsonline (assume) . Click the create button. First, it will check whether this website name already exists or not. If exists you will a warning to change it. If the website created you will get like this.

How to publish your website for free-after-website-created
How to publish your website for free-after-website-created

Now you have so many options like website builder, WordPress, WiX and file manager. You can check other options but here we will see how to upload your own website. For doing this click on file manager.

After that, you will get a panel to upload your website or create files. You can upload a zip file that contains your website files. I will upload an index.php file that has this code.

Publish your website

<?php
    echo "Hey ! I have uploaded my website !";
 ?>

Now your website URL will be http://codingbirdsonline.000webhostapp.com/

Congratulations !!, You have uploaded, hosted your own website free of cost. If you face any problem or missing some steps feel free to comment, I will help you. If you like this article please share it with your friends also.

Happy Coding 🙂

If you are looking to learn how to create a loading spinner or put a loading icon when there is ajax request or form submission then you are in right place.

Hi there I am Ankit, I will tell you how to code to make a loading indicator that shows that the server is busy with some ajax requests. You can check our demo.
 
Creating a busy indicator, or spinner loader is required when you fetch records from the server, then obviously it may take time depending upon the number of records in database or internet speed or both.
In most of the web applications or websites ajax request is created.

Why need loading spinner ?

Example: If you are on Railway websites booking a ticket then you search for a train, what you see? You see a loading icon that says please wait…
 
But actually, in the background, there may be n number of ajax requests. Developers place a loading icon to show that there is something processing.
 
Here I am showing you an example that fetches records from the database. The loading spinner, indicator, leading icon whatever you say will be displayed until all the records not fetched.
 
One thing I will do, the user can’t do anything until data is not loaded. I mean mouse will be disabled for that particular browser tab. Now that’s enough to understand. Let’s make our hands dirty with code.

CSS

Here, This CSS is not mandatory but if you keep it will make user un clickable to page.

th{ color: white; }
.modal-busy {
    position: fixed;
    z-index: 999;
    height: 100%;
    width: 100%;
    top: 0;
    left: 0;
    background-color: Black;
    filter: alpha(opacity=60);
    opacity: 0.6;
    -moz-opacity: 0.8;
}
.center-busy {
    z-index: 1000;
    margin: 300px auto;
    padding: 0px;
    width: 130px;
    filter: alpha(opacity=100);
    opacity: 1;
    -moz-opacity: 1;
}
.center-busy img {
    height: 128px;
    width: 128px;
}

<div> making unclickable

<div class="modal-busy" id="loader" style="display: none">
    <div class="center-busy" id="test-git">
        <img alt="" src="ajax-loading.gif" />
    </div>
</div>

ajax.js

This code fetches the records from the server using AJAX request, and responsible to show loader icon until data is not fully loaded.

$(document).ready(function () {
    $("#loader").show();
    $.post("script.php",{api:"getData"},function (response) {
        var data = response.split('^');
        $("#tbody").html(data[1]);
        $("#loader").hide();
    });
});

script.php

This code the actual logic that fetches the records from the database by SQL query.

<?php
include "config.php";
include_once "Common.php";
if (isset($_POST['api']) == "getData") {
    $sr = 1;
    $tableData = '';
    $common = new Common();
    $data = $common->getData($connection);
    if ($data->num_rows > 0 ){
        while ($row = $data->fetch_object()) {
            $tableData .= '<tr>
                    <td>'.$sr.'</td>
                    <td>'.$row->name.'</td>
                    <td>'.$row->class.'</td>
                    <td>'.$row->marks.'</td>
                    <td>'.$row->gender.'</td>
        </tr>';
            $sr++;
        }
        echo 'test^'.$tableData;
    }
}

This file includes config.php & Common.php. The code is given below.

Config.php

<?php
    $connection = new mysqli("localhost","root","","codingbirds");
    if (!$connection) {
        die("Error in database connection". $connection->connect_error);
    }
?>

Common.php

<?php
class Common
{
    public function getData($connection) {
        $query = "SELECT * FROM bird_records";
        $result = $connection->query($query);
        return $result;
    }
}

I have given the code in parts so that I can make you understand. Now here is the complete code

Complete Code

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/
uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" 
type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/
3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/
3.4.1/jquery.min.js"</script>
    <script src="ajax.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/
    bootstrap.min.js"></script>
    <style>
        th{ color: white; }
        .modal-busy {
            position: fixed;
            z-index: 999;
            height: 100%;
            width: 100%;
            top: 0;
            left: 0;
            background-color: Black;
            filter: alpha(opacity=60);
            opacity: 0.6;
            -moz-opacity: 0.8;
        }
        .center-busy {
            z-index: 1000;
            margin: 300px auto;
            padding: 0px;
            width: 130px;
            filter: alpha(opacity=100);
            opacity: 1;
            -moz-opacity: 1;
        }
        .center-busy img {
            height: 128px;
            width: 128px;
        }
    </style>
</head>
<body>

<div class="container" style="margin-top: 50px;">
    <center>
        <img width="50"  src="https://codingbirdsonline.com/wp-content/
   uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png"/>
    </center>
    <h2>Create loading spinner indicator in jquery ajax,
 while data loads</h2>
    <p>How to create loading spinner indicator in jquery ajax</p>
    <table class="table">
        <thead>
        <tr style="background-color: #1573ff">
            <th>Sr.No</th>
            <th>Name</th>
            <th>Class</th>
            <th>Marks</th>
            <th>Gender</th>
        </tr>
        </thead>
        <tbody id="tbody"></tbody>
    </table>
</div>
</body>
<div class="modal-busy" id="loader" style="display: none">
    <div class="center-busy" id="test-git">
        <img alt="" src="ajax-loading.gif" />
    </div>
</div>
</html>

I hope you got how to do this. If you face any error or missing any steps then you can download the source code from here.

Thanks for visiting Happy Coding 🙂

You have done training or internship in PHP and understood the basics, oops concepts, build some projects … Cool.

 Now if you are looking to learn something new on PHP  then this post is going to be useful for you.
Hi there, I am Ankit, will try to make you understand what should you learn after core PHP. Well… There are verify of frameworks on PHP but I will suggest learning the easiest and light-weighted first.

The most popular and trending framework is Laravel. Then you must be thinking “I should learn Laravel ? “.  Of course, you can but if talk about simplicity and easiness then there is no other framework except CodeIgniter. Here we will talk about it.

From my experience, I will suggest CodeIgniter, the first framework to learn.
It is always a good practice to start with small & simple things to learn. If you want to continue you have to learn more than 1 framework.

Once you start with something simple you can get into more complex frameworks like Yii, Symphony, CakePHP, Zend, Laravel, etc.

What is CodeIgniter?

CodeIgniter is a very easy, simple, lightweight, MVC framework of PHP for developing applications rapidly in an easy way. MVC stands for Model View Controller. CodeIgniter’s libraries are out of the box for connecting to the database and performing various operations like sending emails, uploading files, managing sessions, etc. Read more about Library & Frameworks.

Why learn CodeIgniter?

Easy to install

CodeIgniter is also called CI in short. CI has a system folder and index.php.Installation is very easy unlike other PHP frameworks, the Composer is not required for installation.  Just download the stable version from here and extract it to the root directory of your server. Change the base URL in config.php, you are ready to go.

Easy to learn

CI is simply has everything you required to write good code like MCV, Query builders and helper. It takes a couple of weeks to code confidently in CodeIgniter.

CI’s official user guide is excellent with plenty of examples of every topic. It also used in REST API development for mobile applications and making HTTP requests.

After your experience with the easiest and light-weighted CI, Laravel is now easier to pick up. You can do the same thing in different ways. Laravel seems to be a better MCV framework than CodeIgniter but its docs are not good as CI.

Most of the website you visit to get the definition of the framework in software term but unfortunately these definitions are not able to provide you the whole perspective and this question is most of the time is asked in verify of interviews .so trust me this post is gonna for you to completely understand  difference between library and framework. So without wasting any time, let’s get started…


Now let me tell the what the issue is many people say to try to understand what is a library and what is the framework and you get both answers but this is not perfectly a correct thing,  we have to understand both sides by side.


I will explain the framework in a simple way.
Suppose you have to make tea on a daily basis with several ingredients like sugar, tea leaves, other spices, water, etc. In doing this on a regular basis you find it really difficult to put all ingredients in the right ratio all the time. You may miss any item some time and you have to open several boxes one by one.

So one day you got an idea mixing all ingredients in one jar one ratio such that every spoon serves the right ratio mix to tea(excluding milk and water).


Now the jar is your framework. When you have to do a lot of things on a regular basis it requires a lot of time but the framework not only saves time, it also provides a lot of components to your application. Fast and easy.
On the other hand, When you have fewer rules it is a library and when you have more rules and restrictions, of course, it is going to be a framework.
Let’s take an example.


Home and school and you are a student. When you are at home you can place your books, band anywhere you want. But when you are in school you are restricted to come in proper uniform, place your books and bags in the table.


In the same way, you can do anything with the library, modify and use it. In framework you are bounded by rules, you are not allowed to change, yes you can change, but it requires a lot of settings and configuration changes.


In other ways when you have the power to call a  code whenever you like, it is simply a library. In frameworks, It calls the code and your code might call the library. But in framework let it is CodeIgniter, you are restricted like your helper folder should always be a helper, can you change it? Of course, you can, but need to dig up in settings, configurations. API is a bridge that connects the framework and library.


Libraries are a collection of codes, functions that save your time by implementing all the functionality you want. There are different libraries for different tasks. You may not know how the functions inside the library perform their job. You just need to know how to call the library.


While frameworks are just like a library in a way that makes your job easier but you can not call framework as a library you call. If you want to use a framework, you have to learn first. 

Flask is the web development light-weighted framework.  In order to do this, it needs to do some configuration to your machine that is I am going to tell you in this post.

First of all, you need to download Python 2.7 from its official website. And install it to your system.

Now you will get the folder which is Python 27 in your C drive. Now open it and copy the path and go to your desktop and right-click on My Computer icon and click on properties.

After that, a small window appears and in the right bottom, you get a button named Environment Variable, click on it.

Now you will get two boxes of System and User respectively. Under the System, box click on path variable and Paste then the path that you copied it in beginning.

Now open your CMD and go to your Python 27 and Scripts directly by CMD.

This image has an empty alt attribute; its file name is how-to-configure-flask-in-python.png

When you are inside it just type the command: pip install flask

And hit enter, it may take 2 or 3 mins depending upon your INTERNET speed.

Now make your project folder in any directory in your system. In my case let say I have created it in E drive and inside it create another folder named app and again inside it make two folder named templates and static respectively.

Now open any text editor any type then simple hello world! Application code.

This image has an empty alt attribute; its file name is how-to-configure-flask-in-python-codesnipts.png

Now open again CMD and run the code like this it in the same directory as I told above

E>: CD flask

E:>flask > CD app

E: flask> app python __init__.py

Http://127.0.0.1:5000/ is running on…

Something like this will be shown if everything is correct. Now open the browser and type the same URL and see the result.

Since Python is case sensitive language so make sure you have typed the same code as above.

Conclusion

I hope you learned explained above, If you have any suggestions, are appreciated. And if you have any errors comment here.

Ok, Thanks for reading this article, see you in the next post.

Happy Coding 🙂

If you face any problem regarding configuration or running the code then you can watch this video.

If you want to integrate CKEditor in your web app, then you in the right place. When we create a website or web application, there are some Form fields on your page when you type on that you can not make text formatting, underline, bold, italic, etc. I have an amazing thing that can perform all these tasks that you want. You can also download it from here and link it to your pages. So without any waste of time lets introduce CKEditor. You can check this beautiful demo.

What it does

  • Basic Text Styles: Bold, Italic and More
  • Using the Copy Formatting Feature
  • Removing Text Formatting
  • Applying Styles to Editor Content
  • Applying Block-Level Text Formats
  • Setting Text and Background Color
  • Source Code Editing
  • HTML Output Formatting
  • Pasting Content from Microsoft Word
  • Inserting Code Snippets
  • Table Creation

How to Integrate into your website

in order to integrate it just follow some easy steps :
<script src="https://cdn.ckeditor.com/4.13.0/standard/ckeditor.js"></script>

And wherever you want to place your editor then put this code

<textarea name="editor1"></textarea>
 <script>
     CKEDITOR.replace( 'editor1' );
 </script>

Hence the Final code would be as :

<html>
     <head>
	 <meta charset="utf-8">
	  <title>CKEditor Tutorial by Geekquench.com</title>
	<script src="https://cdn.ckeditor.com/4.8.0/standard/ckeditor.js"></script>
    </head>
   <body>
	<textarea name="editor1"></textarea>
	<script>
		CKEDITOR.replace( 'editor1' );
	</script>
   </body>
</html>

Congratulations !! 🙂 Now you can integrate CKEditor, nice thing on the web page, Although these steps were very easy if you still face any problem then you can watch this video tells how to integrate CKEditor.

The same thing is told in this video.