Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 54

What is Apache Cordova?

 It allows software programmer to build Apps for mobile devices (Android, iOS, Windows,
Ubuntu OS etc) with HTML, CSS and Javascript.
 Most important thing is - It is open source.

This means, with good coding skills in HTML, CSS and Javascript, one can build an App for
most of the mobile operating systems with help of Cordova, without learning different new
programming languages for various platforms.

Following are the platforms for which one can develop apps using Cordova:

 Android
 iOS
 Windows
 Blackberry
 Firefox OS
 Symbian
 Tizen
 Web OS
 Ubuntu

Architecture of Cordova
Cordova provides us with APIs which can be used to access and stimulate native Mobile
OS features like Geolocation, Accelerometer, Camera, Storage, Notifications etc.

Web App is nothing but a simple webpage created using HTML, and styled using CSS along
with Javascript, jQuery etc for User Interface.
Cordova, lets us create an App, in which our Web App is initialised in a WebView (HTML
Rendering Engine).
Cordova Plugins are components that can be used to utilise the native OS features.
Advantages of Apache Cordova
Following are some of the major advantages to develop applications using Apache
Cordova:

 If you go for native apps, then you will have to learn different languages for different
operating systems. For Example: Java for Android, Objective C or Swift for iOS, .NET for
Windows and so on. But with Apache Cordova, you can build app for multiple platforms
in one go, without learning new programming languages.
 Development is fast, as one application developed in HTML, CSS and Javascript can be
easily transformed into apps supported by other platforms.
 Best suited for early stage Startups, as product can be launched on multiple platforms at
once. And maintaining the app is super easy.
 It's very quick to prototype.
 As designing involves CSS, hence it becomes easier to produce great design easily,
without the trouble of native UI design for iOS, Android etc.

Command Line Interface


Command Line Interface(CLI) is a text-based interface that is used to operate software
and operating systems while allowing the user to respond to visual prompts by typing simple
commands into the interface and receiving a reply in the same way. CLI is quite different
from the Graphical User Interface(GUI) that is presently being used in the latest operating
systems.
We also call it Terminal in Mac OS or Command Prompt in Windows operating system.

 In Linux Or Mac we call it Native CLI Terminal.


 In Windows we call it Native CLI CMD(Command Prompt).

What role does CLI play in Cordova?


 Cordova is totally dependent on CLI, so without it we can't execute a single process.
 It is used,
1. To create a cordova project.
2. To add platform for which we want to develop app.
3. To add plugins.
4. To generate APK.

For these listed tasks, we have to pass command line arguments.

How to open CMD in Windows OS?

1. Search cmd in the Menu search bar by typing cmd or command prompt, then click on
the Command Prompt App option in search results.
2. We can also press Ctrl + R to open RUN dialog box, and type in cmd to open
Command Prompt.

3. It will open a black colored screen, this is the command prompt. Step 1 will open cmd in
normal mode.

4. To open command prompt in administrator mode, search cmd in searchbar and click
right button of mouse and choose option Run as administrator.
Following are some useful commands, used in day-to-day work:

o cls → Clear the Command Prompt screen

o cd [directory_path] → To go to any directory

o cd .. → To come out of any directory, to its immediate parent directory.

o mkdir [directory_name] → This command is used to create any directory.

o ipconfig → To get information about your IP address and DNS related info.

Opening Terminal in Mac OS

6. Press Command + Space to open Spotlight Search, and type terminal in the search
field.
7. And click on the Terminal - Utilities option to open the Terminal.
Tools for App Development
Now we will learn about the various tools which we will require for App development. We
have to download 5 different tools:

1. NodeJS
2. Cordova CLI
3. Apache Ant
4. Android SDK
5. Java JDK

NodeJS
NodeJS is a JavaScript runtime and is open source. We use NodeJS to execute backend
code written in Javascript. It is made on Chrome V8 javascript engine. It is lightweight and
very efficient.
NodeJS's package is npm. It is one of the largest ecosystem of open source libraries. We will
use npm to download Cordova, JS libraries, various plugins, packages etc.

Cordova CLI
The command line interface of cordova is used
to create, build, deploy and manage applications based on cordova. From creating project
to building the executable file, we will use command line interface in this tutorial.

Apache Ant
It's main objective is to build a Java application. It is a JavaScript library which is also run
using command line. Or you can say it is a build tool. Using Ant, we can create Ant build
files with all the details about how to compile, assemble, test and run a particular Java
applications.
Android SDK
It is a Software Development Kit(SDK) which includes all the necessary libraries required
to build Android App. So if we wish to develop Android Apps, we need this.

Java JDK
It is Java Develoment Kit (JDK) which is used to develop Java Applications. Again very
important.

As in this quick tutorial, we will be developing an Android Application using Cordova, hence,
the above mentioned tools. In the next tutorial, we will learn how to setup all these tools on
your computer/laptop.

Tools Installation
Now we start installation of tools on Windows OS, one by one.

Installing NodeJS
First of all we need to download and install NodeJS. You can download it from, here. Scroll
down and you will see two download option with title Download for Windows. Download
the most stable version of Nodejs. Stable version is prefixed with LTS
Once the download is finished, you need to install it. To install, simply double click on the
file just downloded. After installation, open cmd and type node -v. If it shows vx.y.z(x,y,z
are numbers), then you have succesfully installed it.
Next type npm -v. If it also shows x.y.z(x,y,z are numbers), then everything is installed
correctly.
If cmd is throwing error, while executing any of the above command, then check it in
the Node.JS Command Prompt.

How to open NodeJs command prompt


Simply by searching node in the searchbar.

If Nodejs cmd is also throwing error, then you have to remove NodeJS and install it once
again and follow the same process.

Installing Cordova
Type npm install -g cordova in cmd or node cmd. Once the installation is complete,
check it by typing cordova -v.
If it is showing version (x.y.z), then you have succesfully installed cordova.

Installing Java Development Kit (JDK)


Follow this link,

Download X64 .exe jdk for 64 bit windows. Download X86 .exe jdk for 32 bit Windows
operating system.
If you don't know which version of Windows OS you have, just select Properties option
from the menu, after a right click on My PC or My Computer.
There you will see the version no. (16bit, 32bit, 64bit) of your computer/laptop, against the
label System type

After successful installation of JDK. Next step is to add it to our system's path variable.

How to open and update Path variable


Search for environment variable in the serach bar. Choose the option Edit the system
environment variables, it will show you a new dialog window.

Click on the button Environment variables, available at the bottom of the dialog box.

Now add a system variable and name it JAVA_HOME, and add another system variable
with the name as, _JAVA_OPTIONS.
To understand the values that we have to assign to the system
varibales JAVA_HOME and _JAVA_OPTIONS, please check the addresses specified
below:
Address of Java JDK will be c:\Program Files\Java\jdk_(x.y.z_k). Lets assume this to
be address 1
Address of 'bin' will be c:\Program Files\Java\jdk_(x.y.z_k)\bin. Lets assume this to
be address 2
Address of JRE 'bin' will be c:\Program Files\Java\jre_(x.y.z_k)\bin. Lets assume this to
be address 2a
Now add address 1 as the varibale value for variable name, JAVA_HOME. And in the
System Variable box, there is a variable with name, path. Add address 2 and address
2a as the variable value for path variable by separating the values with semicolon ;. For
Example: address 2;address 2a

Next add address 2 and address 2a as the variable values for the User
Variable PATH (User variable panel is just above the System Variable).
And add -Xmx512M, as the varibale value for System variable _JAVA_OPTIONS.
Save all these changes and restart cmd then type javac -version. If it shows the version,
then you have successfully installed Java.

Installing Apache Ant


Follow this link and download the latest zip file, and extract it wherever you want to keep it.
Let us supose you extracted it in users/[system_name]/ant location.
The location of ant will be users/[system_name]/apache_ant_x.y.z (x.y.z will be anything
1.10.1,1.9.7,...). Lets assume this to be address 3
The location of bin will be users/[system_name]/apache_ant_x.y.z/bin (x.y.z will be anything
1.10.1,1.9.7,...). Lets assume this to be address 3a
Now create a new System variable ANT_HOME and add address 3 as the variable value.

And in path and PATH add address 3a, to the exisiing values, by using a smeicolon ;
After saving all the changes, restart cmd and type ant -v. If it displays the same version
number as we downloaded, then you have installed apache ant.

Installation of Android SDK


Follow this link: https://dl.google.com/android/installer_r24.4.1-windows.exe
After installation look for the directory in which Android SDK tools and Platform tools are
installed. In my computer it is installed at, C:\Users\[system_name]\

Here we have the complete directory structure of Android SDK, out of which 2 directories
are important for us, they are:
C:\Users\[User_name]\AppData\Local\Android\android-
sdk\tools and C:\Users\[User_name]\AppData\Local\Android\android-sdk\platform-
tools"

Now create a new System Variable ANDROID_HOME and add only the Android SDK
directory as the variable value.
And in path variable, add platform tools directory and tools directory of Android SDK.
Now save all the changes, restart cmd and type android.
A new screen will pop up, congrates! you have successfully installed Android SDK.

In the new window, check (tick mark) the checkboxes to download only Android SDK tools,
Android SDK platform-tools, SDK build tool in tool panel and download SDK platform etc.
From next lesson we will start with development of App.

Programming Languages required


For App DJevelopment in Cordova we use HTML, CSS, JS, various libraries such
as: Bootstap, jQuery, Angular) etc.

HTML
Hyper Text Markup Language is used to create the DOM structure for any webpage. It's
main motive is to show content on the screen when opened in a broswer.
HTML basic structure:
<html>

<head>

<title> </title>

</head>

<body>

</body>
</html>

If you are new to HTML, learn it from here: HTML Course.

CSS
Cascading Style Sheets is used to style the HTML content to make it look good.
CSS basic structure:
Suppose we have to provide a background color to the content of body.
<style type="text/css">

body{

background-color: blue;

</style>

We put this style tag in the head tag.


<head>

<style>

//CSS Code

</style>

</head>

Or we can write the CSS code in another file and link it to our HTML file.
To do this, name a file style.css and write the below sepcified CSS code in this file:
body{

background-color: blue;

p{

background-color: red;

Now to add this CSS file to our HTML code, do the following:
index.html
<head>

<link rel="stylesheet" type="text/css" href="style.css">

</head>

NOTE: While writing CSS code in style.css file, don't include <style> tag now.
JS, or Javascript
We use Javascript to dynamically operate on the content, present in the HTML webpage.
Suppose we have to inject a string, say I am learning using Studytonight to the body of
our HTML webpage, dynamically.
<script type="text/javascript">

document.getElementByTagName('body').innerHTML="I am learning using Studytonight";

</script>

We can either put the javascript code inside the script tag, which is place in the head tag.
<head>

<script>

//Javascript code

</script>

</head>

Or, we can write JS code separately in another file and add it to our pre-existing HTML file.
For example: Write JS code in index.js
index.js
document.getElementByTagName('body').innerHTML="I am learning using Studytonight";

alert("I am learning Hybrid app development on Studytonight ");

prompt("What is your name?");

and in the HTML file, we can add the javascript file,


index.html
<head>

<script type="text/javascript" src="index.js"></script>

</head>

NOTE: Don't include <script> tag in index.js

Javascript Libraries (jQuery.js, Angular.js, React.js)


We use javascript libraries to minimise our efforts. Let's take an example: Suppose you
have to update the content of a div tag, identified by, id="test-div", dynamically. Then
either you can write this code in plane JS or you can use any JS library.
Code in Plane Javascript
document.getElementById('test-div').innerHTML = "I am learning Hybrid App development on Studytonigh
t";
Same code, using jQuery
$('div').html("I am learning Hybrid App development on Studytonight");

NOTE:Second way of writing code is more flexible than the first.

How to use a library?


Include it in your HTML page, just like you added a separate Javascript file and use it.
<head>

<script type="text/javascript" src="library_name.js"></script>

</head>

So the final structure of any HTML page(index.html) is like:


<html>

<head>

<script type="text/javascript" src="library_name.js"></script> //Any library jquery.js etc

<script type="text/javascript" src="index.js"></script> // Your own JS code

<link rel="stylesheet" type="text/css" href="name.css"> // Your own CSS code

<link rel="stylesheet" type="text/css" href="css_library.css"> //CSS library

</head>

<body>

<div id="test-div" ></div>

</body>

</html>

NOTE: One must have knowledge of all these above concepts to use Cordova for App
development.

First Android Application


Now we are ready to create our own first android app using Apache Cordova.

1. Open cmd.
2. Go to the location where you want to create your first application. Suppose you want to
create your first app on desktop. So type the following code in command prompt: cd
desktop, if you are here "C:user\system_name\". The command cd desktop will take

you to desktop location.


3. Type cordova create [project_name] [package_name] [apk_name] and press enter.

project_name → This will be your project name, like myFirstApp. After executing 3rd
step, a folder will be created with the specified name on the desktop. You may check
there.

package_name → Every App has a unique application ID which is known as package


name,
like com.stuytonight.app, com.myfirstapp.android, anything.anything.anyotherthing etc.

apk_name → It is the name of the apk.

4. Type cd [project_name] and press enter, to get inside the project directory.
5. Now we will specify the name of the platform for which we want to create our mobile
application, for example we can inform cordova, that we want to create android
application by using the command, cordova platform add android. It will add android
platform. You can see it in platforms folder, inside the project folder.

6. Type cordova build android. This command will generate the apk.

For first time, Step 5 or Step 6 will take time, because the gradle file will be downloaded.

Your apk's location will be: project_name/platforms/android/build/output/apk.


You can run this apk on emulator or copy it to your android phone and install it there. After
launching the app, you will see the default apache HTML coded screen.
Modifying our App
Now we will add our own files to the app folder after the Step 4.
Our HTML file: index.html
<html>

<head>

<script type="text/javascript" src="index.js"></script>

<link rel="stylesheet" type="text/css" href="name.css">

</head>

<body onload="ask()">

<div id='question'>Tell us your experience on Studytonight</div>

<div id='answer'></div>

</body>

</html>

Our CSS file: style.css


#question {

margin-top:100px;

text-align:center;

color:red;

border: blue solid 2px;

#question:hover {

color:geen;

#answer {

margin-top:30px;

text-align:center;

color:yellow;

border: red solid 2px;

Our Javascript file: index.js


function ask(){

// This function will be called when page will be loaded.


var k = prompt("Tell us your experience on Studytonight");

if(k.length > 0) {

// Before inserting string into the div, it clear it first.

document.getElementById('answer').innerHTML = "";

//Now it will inject string into the div.

document.getElementById('answer').innerHTML = k;

else {

// If length of string is 0, then it will again ask you the same question.

ask();

Now open project_name folder, go to www folder, delete all the pre-existing files and place
all the three file (index.html, index.js and style.css). Then follow the steps 5 & 6 again.

What is config.xml file for?


When you open project_name folder, then you will see a config.xml file. So let's explore
what this file is for? Open this config.xml file in notepad, notepad++, Atom or Sublime, any
good editor.
config.xml is the global configuration file for our project. Every project will have this file. It
specifies the platform, plugins used, first page to open, permissions etc.

1. It specify for which platform, developer wants to create the app.


2. Required plugin.
3. In config.xml, the content tag is used to specify the first page to open,
4. <content src="index.html" />

Whenever the app is opened, it gets redirected to this page index.html. You can edit it
and you can change it to anything like firstpage.html, just by modifying the
configuration in the config.xml file.

Integrating Google Map


Now we will create another quick project, in which we will integrate Google Map into our
Android App.

1. Create a new project. You know how to do this, we just did this in the previous lesson.
2. Now go to Google's Developer Console → https://developers.google.com/maps
3. Scroll down and click on Google Map Javascript API
4. Click on GET A KEY.
5. Now click on Create Project and then name your project and enable API.

6. Copy that key to the clip board.


7. Now it's time for writing HTML, JS and CSS code.
We have integrated the JS, CSS and the HTML code in a single file for this one. If you
want, you can break down this code into 3 separate files.

index.html
<html>

<head>

<style type="text/css">

#map_area {

position:fixed;

height:100%;

width:100%;

top:0;

left:0;

</style>

<script type="text/javascript">

function start() {

var latlong = {lat: 24.801522, lng:84.995989};

var map = new google.maps.Map(document.getElementById('map_area'), {

zoom: 17,

center: latlong

});

var marker = new google.maps.Marker({

position: latlong,

map: map

});

</script>

</head>

<body>

<div id="map_area"></div>

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=start"><script
>

</body>

</html>

8. Place the above code in your index.html file, and put the file inside the www folder.
9. Pass the command to generate the apk file.
10. Transfer this apk to your phone and test it.

Cordova Plugin
Plugina allow applications developed with Cordova to access the device's functionality.
Plugins are written in JavaScript and native libraries. All the cordova main features are
implemented as plugins. If we don't use plugin then we can't use any of the native features.

Why we use plugin?


Let us suppose you want to access Gallery or Contacts of the device, in such a situation we
need plugins, which will communicate with device and request device to grant the required
permission.
NOTE: You can also create your own plugin.
For example:
Suppose you want to pick a contact from the contact list, then how will you do this through
your app, so here we need plugin which communicate with native feature of device and
request to grant permission.
Like, if you want a mango from tree, but tree is not yours, then what you do, you first ask the
owner of the tree, if he grants permission then only you can pick the mango, but if he
dowsn't allow you, then you can't go ahead and pick the mango. In the same way plugin ask
for permission and also provides a way to act on the permissions.

Types of Plugins
There are many types of plugin, some are:

1. Camera Plugin (To open camera)


2. Geoloation Plugin (It captures your location cordinates → latitude, longitude)
3. File Transfer Plugin (It transfers the file from your storage to somewhere else → say to
the server)
4. Contact List Plugin
5. Push Notification Plugin

Using Cordova Plugin in your App


Plugin can be integrated into your application through command line. After adding platform,
we pass another command to integrate plugin(optional).
For Example:
To add Camera plugin, type cordova plugin add cordova-plugin-camera.
Above command will add Camera plugin, now you can use functions to call it.
Using GeoLocation Plugin
Let's create an app which collects your location coordinates and show it on Google Map.
We have already created an app with Google Map integration, now we will create another
application which will show your device's location on Google Map.

1. Create project.
2. Add platform → android
3. Add geolocation plugin - Type cordova plugin add cordova-plugin-geolcation and
press enter.
4. Now write the following code in your index.html file and put it in www directory in the
project folder.
5. <html>

6. <head>

7. <style type="text/css">

8. #map_area {

9. position:fixed;

10. height:100%;

11. width:100%;

12. top:0;

13. left:0;

14. }

15. </style>

16. <script type="text/javascript">

17. function getLocation() {

18. if (navigator.geolocation) {

19. function showLocation(position) {

20. var latitude = position.coords.latitude;

21. var longitude = position.coords.longitude;

22. }

23. navigator.geolocation.getCurrentPosition(showPosition);

24. }

25. else {

26. alert('Not allowed by device');

27. }

28. }

29.
30. function showPosition(position) {

31. var lat = (position.coords.latitude);

32. var long = (position.coords.longitude);

33.

34. start(lat, long);

35. }

36.

37. function start(lat, long) {

38. var latlong = {lat: lat, lng: long};

39. var map = new google.maps.Map(document.getElementById('map_area'), {

40. zoom: 15,

41. center: latlong

42. });

43. var marker = new google.maps.Marker({

44. position: latlong,

45. map: map

46. });

47. }

48. </script>

49. </head>

50. <body>

51. <div id="map_area"></div>

52. <script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=getLocation"><


script>

53.

54. </body>

55. </html>

After the script loads successfully, it will call geo Location function. This function
requests the device to grant the required permission. If the device grants permission, it
will pass the latitude and longitude to start function. And your device location will be
shown on the map.

Introduction to AJAX
AJAX stands for Asynchronous Javascript And XML. It is a client-side script used in
Javascript to communicate with server to exchange data or anything without refreshing the
page.
Let us suppose we want to make a dynamic cordova based application where user needs to
exchange data with server, say login credential verification, so we can use AJAX to send
the data to the server and through the same gateway server, send the result back to the
user.
Ajax basic code: We will use jquery.
$.ajax is a jQuery function to make http POST, GET etc request to the server and receive
results without the page being refreshed or reloaded.
$.ajax({

type : 'get', //Request method: GET, POST

url : 'http://studytonight.php/login.php', //Where to send the data

data: {name, password}, //What data you want to send

success:function(data) {

//Here you will receive data from server

//Do what you want to do with data

console.log(data) //This is a example, like we want to print the result

})

NOTE: Covering Ajax and jQuery is not in the scope of this tutorial. But we strongly advice
you to learn abour Ajax, as it is very useful if you want to create dynamic Apps.

Connection with the Backend


Now we will learn, How to connect our cordova based application with the backend to work
dynamically with data.
Backend Language → PHP
Database → MYSQL
Have you ever thought, when you feed your username and password in some login form,
what happens? How does it verifies your credentials? So, let's try to understand and
implement credentials verfication.
When you enter your username and password, the client (browser, in most cases or the
app) sends your username, password and some header data to server (say PHP based
server and MySQL based database). There Php receives your data and act accordingly. An
SQL query is executed to fetch the data, which is then compared with the username and
password submitted. And it send back the result through the same gateway, then client-side
also responds as per the response received (like, server response is incorrect
parameters, then client side will show you Username and password does not
match. message).
Now in this tutorial, we will create an app which will communicate with the backend. For this
we require XAMPP(https://www.apachefriends.org/index.html) application. Follow the link
and download XAMPP and install it. XAMPP is a local server, which runs Apache, Php and
MySQL for developing and testing websites and apps on your local machine. It replicates a
LAMP web server locally on your laptop/computer.

1. After installing, open XAMPP server and click on Start corresponding


to Apache and MySQL.

NOTE: Default port for the server is 80.

2. Now write some code in Php and place it in the htdocs folder inside the XAMPP folder.

index.php

<?php
echo “hello world!”;

3. Open the browser and type in the address bar: http://localhost or http://127.0.0.1, it
should show hello world! on the screen.
This means our XAMPP server is running successfully. Now we are ready to develop a
dynamic mobile app. Client-side script (HTML, CSS, Javascript and jQuery, just like in
previous tutorials). Keep the jquery.js file with index.html (or both in same folder)

4. Here is the index.html file.


5. <html>

6. <head>

7. <script type=”text/javascript” src=”jquery.js”></script>

8. <script type=”text/javascript”>

9. $(document).ready(function(){

10. $(“#sub”).click(function(){

11. var firstname = $(“#firstname”).val();

12. var lastname = $(“#lastname”).val();

13. if($.trim(firstname).length >0 & $.trim(lastname).length >0) {

14. $.ajax({

15. type:”POST”, //Request type

16. url: “http://localhost/firstname.php”,

17. data:{firstname:firstname, lastname:lastname},

18. cache:false,

19. success:function(data) {

20. alert(data);

21. }

22. })

23. }

24. else {

25. alert(‘Input fields are empty’);

26. }

27. })

28. })

29. </script>

30. </head>

31. <body>

32. <input type=”text” placeholder=”write your first name” id=”firstname”>

33. <input type=”text” placeholder=”write your last name” id=”lastname”>

34. <button id=”sub”>Submit result</button>

35. </body>
36. </html>

and the firstname.php


<?php

$firstname = $_POST[‘firstname’];

$lastname = $_POST[‘lastname’];

echo $firstname.” “.$lastname;

?>

Now place this PHP file and the HTML file in the htdocs folder. And make sure your
XAMPP server is running. Run the index.html in browser and feed input and check
output.

Migrating the Code to Android App


Now we will run this code in mobile, so first connect your laptop and mobile (In which you
will test your app) with the same hotspot. Then once connection is setup, open cmd in your
laptop/computer, type ipconfig and press enter. It will show the IP addresses, if your
computer is connected with WIFI router then copy the IP of wireless LAN adapter adapter
wifi, else copy the LAN IP address. Replace the localhost (url attribute
inside $.ajax function in index.html) with this IP address.
We only need the index.html file in the App, firstname.php file will remain in
the htdocs folder of XAMPP directory.
Now generate the apk. Copy it to your device and check whether it is working or not.
In case it is not working, make sure your server is running or not? Whether both the devices
are connected to same wifi hotspot network or not? If connected to same wifi network,
check the IP address. Next, we will save user's input into our MySQL database.
For this, first we will have to create MySQL database.

1. Open http://localhost/phpmyadmin in the browser.

2. Click on SQL
3. Type the following command in the textarea and click on Go.
CREATE DATABASE mydb;

This command will create database mydb if it does not exist already.
4. Now open the mydb database, by clicking on it in the sidebar and once again click on
SQL. Then create table using the following command.
5. CREATE TABLE my_table (

6. id int AUTO_INCREMENT,

7. firstname varchar(200),

8. lastname varchar(200)

9. )
It will create a table with name, my_table in mydb database.

10. Client side code i.e. index.html file, will remain the same but the Php side code will
change.
firstname.php
<?php

/*

localhost is the location where the server is located

root is the global username of server

' ' this root has no password protection, hence empty

my_db is db with which we want to connect

*/

$con = mysqli_connect(‘localhost’,’root’,’’,’my_db) or die (‘unable to connect’);

$firstname = $_POST[‘firstname’];

$lastname = $_POST[‘lastname’];

$sql = “INSERT INTO `my_table`(`firstname`,`lastname`) VALUES(‘$firstname’,’$lastname’);

$result = mysqli_query($con,$sql);

if($result) {

echo $firstname.” “.$lastname;

else {

echo “unable to insert data”;

?>

Now try it or refresh phpmyadmin page and check whether the data is inserted or not.

You might also like