Php Tutorial - Series (#1) - Php for beginners

in #utopian-io7 years ago (edited)

Introduction

If you are a beginner looking for a simple-clear-precise way to learn php then you have come to the right place.

Below are the tutorials for core php programming. We assume that you are new to php programming but have a basic idea on programming. Once you are done with these series, you can go to advanced php programming and then to Frameworks.

What Will I Learn?

  • Know all the basic concepts of php programming
  • Write php programs.
  • Interact with databases to insert and retrieve data.
  • Interact with html forms to get the data and save them in database

Requirements

  • basic html
  • basic idea on general programming

Difficulty

  • Basic

Advantages of php - top 10 php sites

  1. The services provided by the internet like email, e-commerce, forums, social networking sites, CRM, online reservations- air ticket booking, hotel booking, etc are all database driven applications.
    You can develop any of the above web applications using php! (of course integrating with other technologies such as Mysql etc..).
  2. Php's most significant feature is that it supports all major databases including MySQL, PostgreSQL, Oracle, Sybase, MS SQL, DB2 and nosql databases like MongoDB, CouchDB etc..
  3. Most used Content Management Systems(CMS's) such as Wordpress,Drupal, Joomla, forum softwares like phpBB are all based on php.
  4. There are ready-to-go ecommerce web applications built on php frameworks- like Magento Commerce, osCommerce, drupal-Ubercart, Zen Cart, PrestaShop and many more.. all of them are free to use.
  5. The fact that php is exclusively built for the web made it very popular!```
  6. There is no need to compile php code before executing, unlike other programming languages.
  7. Php has an automatic garbage collector.
  8. Php is faster in the development phase and it is easier to scale.
  9. Php is cross platform, cross server, cross database and open source.
  10. All the hosting providers support php including Microsoft Windows Azure.

The advantages of php can not be under-estimated.

In fact there are many hosting sites which provide free hosting for php.
(www.000webhost.com/free-php-hosting, http://www.zymic.com/free-web-hosting, www.byethost.com/free-hosting, www.awardspace.com, www.freehostia.com/free-php-hosting.html).

There are lots of books available to learn php and there is huge community support.
Top 10 High Traffic Websites which are built on PHP-
Facebook, Yahoo!, Flickr, Wikipedia, Eclipse.org, Photobucket.com, Digg.com, Apple.com, Youku.com, Baidu.com.

How to install php on windows - ubuntu

In order to execute php code you need to install php software.

  • Xampp is an application package that will run local server in your computer.
  • Download and install xampp (for windows). It includes php, web server software (Apache), database server(MySQL) and Perl (download xampp)
    Xampp stands for X-cross platform, apache(web server), Mysql(database server), php and perl
  • Once the installation is done, you can start apache and mysql using the control panel
    Ubuntu install-
  • Open the terminal
  • Type in-wget http://www.apachefriends.org/download.php?xampp-linux-1.8.1.tar.gz
  • This will download xampp for linux
  • To install xampp type- sudo tar xvfz xampp-linux-1.8.1.tar.gz -C /opt
  • To start the server type- /opt/lampp/lampp start or service httpd start/restart (to start and restart when required).

Once you start the server open your browser and type the following url-
http://localhost if the web server package is successfully installed you will see the apache friends page with a number of links.

Important files and directories-

xampp/bin/mysql -u root -p
This will call the mysql monitor
xampp/htdocs/

The Apache document root directory
-this is where our project files/folders go.
xampp/etc/httpd.conf

The apache configuration file
xampp/etc/my.cnf

Mysql configuration file
xampp/etc/php.ini
The php configuration file.

Php basic terminology

Commonly used terminology in php-

Web server-

A web server is a software to run web applications, handles requests from browser and sends response to the browser.
Ex: Apache, Nginx, IIS, Zend server etc.

Web browser-

Its a program to open the web applications/websites from the web servers.
Ex: Firefox, Safari, Chrome, Internet Explorer etc.

Client side language-

The script which executes in clients browser is called client-side language.
Ex: HTML, JavaScript, JQuery etc.

Server side language-

The script which executes in the web server is called server side language.
Ex: PHP, Python, ASP, JSP etc.

What is a Request?

Request is a trip of web page from client to server.

What is a Response?

The output sent from the web server to the browser is known as response.
WAMP- Windows, Apache, MySQL and PHP.

LAMP- Linux, Apache, MySQL and PHP.

XAMPP- It will support different operating systems. 'X' stands for cross-platform.

MAMP- Macintosh, Apache, MySQL, PHP.

Core php-

A php application can be developed using both procedural approach and Object-oriented programming approach. the procedural approach is usually considered as core php.

Framework-

A web framework provides libraries for database access, templates, session management and they promote code re-use. It will take care of the low level services so that the programmer can focus on business logic.

Usually, all the frameworks use Object-oriented programming approach.
Ex: Zend Framework, Codeigniter, Symphony, Cakephp etc.

What is a CMS?

A content management system is a web application made especially for non-technical people to create, edit, publish their content on a website.
Ex: Word Press, Drupal, Joomla etc.

Protocol-

A protocol is a set of instructions to transfer the data from one location to another in a network.
Stateful Protocol-

These protocols can maintain the state of the application ie., they can remember all the previous request and response values.
ex: tcp/ip protocol- desktop applications

Stateless protocol-

These protocols can not maintain the state of the applications ie., they do not remember the previous request and response values from current request and response values.
ex: http protocol- web applications

State management-

Cookie and sessions are state management objects which help in maintaining state of an application ie., using these two we can make them remember

Php mysql create table

  • MySQL is the-most-popular database management system for PHP.
  • Before we write our first program we will create a database using PhpMyAdmin.
  • Before creating a table we will have to create a database to contain that table.
  1. Open the browser type- http://localhost/phpmyadmin and click on sql tab on the top.
  2. The syntax to create a database is- create database database_name (ex:create database users) and click on go.
  3. Once the database is created, select the database shown in the left panel and click on the sql tab again.
  4. Now we will create a table to store the data: the syntax for creating a table is- create table table_name(column_name datatype, ..) ex: create table user_details(uname varchar(25), pwd varchar(25), email varchar(25), addr varchar(50)) and click go!.
  5. We can see the database and its tables by clicking on the particular database from the left panel.

You can also access MySQL monitor to create a database / table from the SQL command line (This is a command line interface)-

  1. Go to c:\xampp\mysql\bin> and type mysql -u root -p and press enter. it will prompt for password since we didn't set a password just press enter.
  2. Just follow the previous steps to create the database- create database users.
  3. Once the query is executed successfully we have to select the database to create a table. To select a database the syntax is- use database_name (Ex:use users).
    4.Now we are inside the database, to create a table just follow the syntax to create the table.
    Once we are done with creating the required database and table we can write a php script which can take the input from user and save it in the database.

Php example code

  • We will use 2 files to create our required php example code-
  • Open notepad and save (in root folder under C:\xampp\htdocs) the files with the following name and extension.
  1. register.html
  2. code.php
    Copy/save the following code into the register.html file-
<html>
<body>
<form method="post" action="code.php" id="registration">
<table>
<tr><td>Username</td><td><input id="uname"></td></tr>
<tr><td>Password</td><td><input type="password"id="pwd"></td></tr>
<tr><td>Email</td><td><input id="email"></td></tr>
<tr><td>Address</td><td><input id="addr"></td></tr>
</table>
<input type="submit" name="submit" value="Register!">
</form>
</body>
</html>

Copy the following php code into the code.php file-

<?php //this is an indication that the following lines of code are php script.
$con=mysql_connect("localhost","root","password-if-any");
//mysql_connect(hostname,username,password) function is used to connect with mysql database.
mysql_select_db("users",$con);
//mysql_select_db(database_name,connection) is used for selecting the database.
$uname=$_POST['uname'];
$pwd=$_POST['pwd'];
$addr=$_POST['addr'];
$email=$_POST['email'];
//Here $_POST is a php superglobal variable which is used to carry the user input details to the db.php file
$sql="insert into user_details values('$uname','$pwd','$addr','$email')";
if(mysql_query($sql))
//mysql_query(sql_statement) is used for querying the database.
//we can perform all the CRUD (Create,Read, Update, Delete) operations here.
echo "success";
else{
echo "failure";
echo "<br>";
echo mysql_error();
//mysql_error() is used to show the error details if there are any errors while saving the data.
}
?> //this is an indication that the php code is ended here.
  • Now go to http://localhost/register.html. Here you will find the registration form. Enter details and click on register. If you have done everything right you will find success message on the screen.
  • You can check if the registration is successful. [Go to http://localhost/phpmyadmin ->select the database->select the table (user_details)].

Php basic rules

Lets have a look at the basic programming rules which we should follow while programming with php-

  1. Php is a case insensitive language except for naming variables ($Variable is not same as $VariAble).
  2. Php code should be placed within the script declaration tag.
  3. All the variable names should begin with $ symbol. It indicates that you have created a variable. No need to mention the datatype for the variable. Php is intelligent enough to find the data type automatically.
  4. All php files should be saved with an extension .php
  5. Every line in php code should be terminated with ; semicolon.
  6. Anything outside script declaration tags <?php ?> is printed on the screen.
  7. The . dot operator is used for concatenation.
  8. php can be embedded within html.
  9. The output of php is html.
  10. All php applications are executed with the help of a web server.

Php echo | print | print_r | var_dump functions

echo- echo prints the output on browser and it does not return any value if the action is successful.
try this-

<?php
echo "abc","xyz";
?>
**print**- Php's print function will output the result in the browser and returns true if the action is successful.
try this
<?php
$a=print "print function";
echo $a;
?>

Note: Print cannot output multiple strings while echo can.
var_dump- php's var_dump() function prints variable value along with its data type.
try this-

<?php
$a=350;
var_dump($a);
?>
**print_r**- This php function displays all the elements of an array and properties of object.
try this-
<?php
$a=array("text1","text2","text3","text4");
print_r($a);
?>

Note- All these output functions are extremely useful while debugging your application.

Php include - require functions

- We can include or use external php files into our current php application.

By doing this you will be able to access all contents of that external php file (such as functions, variables etc.).

- How to include external file in php

We have different types of functions to include external php files into our current working file-
include() function-

This function includes external php file any number of times. If the external file is not available it returns a warning message and executes the rest of the statements.
try this-

<?php
echo "this is page 1 script!";
$x="page1 variable";
function xy(){
echo "inside xy function";
}
?>

create a file named 'page1.php' in htdocs folder and paste the above code in it.
now we will include this file in page2.php

<?php
**include** 'page1.php';
echo $x; //we are printing $x variable which is in page1.php
xy(); //we are calling xy function which is in page1.php
?>

check the output at localhost/page2.php
include_once() function-
This function includes the file only one time. It ignores the remaining include_once statements which contains the same file name.
require() function-
It is same as include except that it returns fatal error
try this:

<?php
//we don't have any file by the name file1.php
require 'file1.php';
?>
**require_once**() function-

This function is same as the require() function but it embeds the external file only once.
Now you know how to include external php files into your project.

What did we learn, hopefully?

A lot have been discussed in this episode! We discussed advantages of php and a list of top 10 php sites were highlighted. In order to properly execute php code you need to install php software. There is also the need to be acquainted with commonly used terminologies in php.

MySQL is the-most-popular database management system for PHP therefore, Php mysql create table was an indispensable subheading to consider. Discussing Php example code, we used 2 files to create our required php example code; register.html, and code.php.

There are Php basic programming rules which we should follow while programming with php. The tutorial was capped up with Php echo and Php include - require functions

I had fun writing this! I can not wait enough for the next episode. I just love doing this continously!

Thank you for your time!



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

My opinion:

  • Quite interesting this tutorial for beginners, however in the next tutorial try to use more practical examples and less theory about the tools.

You can contact us on Discord.
[utopian-moderator]

Hey @henrysblog I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • This is your first accepted contribution here in Utopian. Welcome!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Congratulations @henrysblog!
Your post was mentioned in the Steemit Hit Parade for newcomers in the following category:

  • Pending payout - Ranked 8 with $ 48,2

I also upvoted your post to increase its reward
If you like my work to promote newcomers and give them more visibility on Steemit, feel free to vote for my witness! You can do it here or use SteemConnect

Hey @henrysblog,
having a look at your TOP 10 PHP sites, I am a little bit confused:

TOP 1 I'am not sure if it is worth to be mentiond as a TOP 1 (you can still use JAVA or Perl to implement such Services)

TOP 2 says, PHP supports a lot of DBs. Keep in mind that you or you'r hoster needs to enable that support, it does not work out of the box (no one of them). MySQL is enabled for the most, IMHO.

TOP 3 is quiet a cool one. But I don't know why that makes PHP so cool. I would have mentioned, that you can quickly start to improve big Systems while learning PHP, that would be a benefit by choosing PHP :)

TOP 4 same as TOP 3

TOP 6 has some bad facts: While the raw Code is uploaded, and many Systems Needs it to be writeable (Auto updates in WordPress bspw.) PHP is hackable. The attacker just Needs to get Access and then can start to modify the source Code. That is a bad aspect on the raw sourcecode. The good Thing is, you can Code PHP using a Basic Editor :)

TOP 7 many programming languages do have a garbage collector

TOP 8 Yes, coding PHP could be fast. But I'am not sure what you mean by "easier to scale"? (Really, would be nice to read about that part)

TOP 9 same as TOP 8

TOP 10 Not all (even in 2018) Hosting Providers do Support PHP. That of Course is a shame o.O

I did not read your whole article. I think it is a Little bit Long for a kick off, dont you think so?