Mysql Installer: Installing Mysql On Windows/ How To Get Mysql
Mysql Installer: Installing Mysql On Windows/ How To Get Mysql
Mysql Installer: Installing Mysql On Windows/ How To Get Mysql
Summary: in this tutorial, you will learn step by step how to install MySQL on the Windows platform using the MySQL Installer. After the
tutorial, you will have a MySQL server and its tools up and running on your system for learning and practicing.
MySQL Server
MySQL Notifier
MySQL Documentation
To download MySQL installer, go to the following link http://dev.mysql.com/downloads/installer/. There are two installer files:
If you are connecting to the internet while installing MySQL, you can choose the online installation version mysql-installer-web-
community-<version>.exe .
In case you want to install MySQL offline, you can download the mysql-installer-community-<version>.exe file.
Install MySQL Step 2 – Welcome Screen: A welcome screen provides several options. Choose the first option: Install MySQL Products
Install MySQL Step 3 – Download the latest MySQL products: MySQL installer checks and downloads the latest MySQL products including
MySQL server, MySQL Workbench, etc.
Install MySQL Step 8 – Configuration Overview. Click the Next button to configure MySQL Database Server
Install MySQL Step 8.1 – MySQL Server Configuration: choose Config Type and MySQL port (3006 by default) and click Next button to
continue.
Install MySQL Step 8.1 – MySQL Server Configuration: choose a password for the root account. Please note the password download and
keep it securely if you are installing MySQL database server on a production server. If you want to add a more MySQL user, you can do it in
this step.
Install MySQL Step 8.1 – MySQL Server Configuration: choose Windows service details including Windows Service Name and account type,
then click Next button to continue.
Install MySQL Step 8.1 – MySQL Server Configuration – In Progress: MySQL Installer is configuring MySQL database server. Wait until it is
done and click the Next button to continue.
Install MySQL Step 8.1 – MySQL Server Configuration – Done. Click the Next button to continue.
Install MySQL Step 8.2 – Configuration Overview: MySQL Installer installs sample databases and sample models.
Install MySQL Step 9 – Installation Completes: the installation completes. Click the Finish button to close the installation wizard and launch
the MySQL Workbench
MySQL uses security based on Access Control Lists (ACLs) for all connections, queries, and other operations that users can attempt to perform. There is also
support for SSL-encrypted connections between MySQL clients and servers. Many of the concepts discussed here are not specific to MySQL at all; the same
general ideas apply to almost all applications.
Do not ever give anyone (except MySQL root accounts) access to the user table in the mysql system database! This is critical.
Learn how the MySQL access privilege system works (see Section 6.2, “Access Control and Account Management” ). Use
the GRANT and REVOKE statements to control access to MySQL. Do not grant more privileges than necessary. Never grant privileges to all hosts.
Checklist:
o Try mysql -u root. If you are able to connect successfully to the server without being asked for a password, anyone can connect to your MySQL
server as the MySQL root user with full privileges! Review the MySQL installation instructions, paying particular attention to the information
about setting a root password. See Section 2.10.4, “Securing the Initial MySQL Account” .
o Use the SHOW GRANTS statement to check which accounts have access to what. Then use the REVOKE statement to remove those privileges
that are not necessary.
Do not store cleartext passwords in your database. If your computer becomes compromised, the intruder can take the full list of passwords and use
them. Instead, use SHA2() or some other one-way hashing function and store the hash value.
To prevent password recovery using rainbow tables, do not use these functions on a plain password; instead, choose some string to be used as a salt, and use
hash(hash(password)+salt) values.
Do not choose passwords from dictionaries. Special programs exist to break passwords. Even passwords like “xfish98” are very bad. Much better
is “duag98” which contains the same word “fish” but typed one key to the left on a standard QWERTY keyboard. Another method is to use a password
that is taken from the first characters of each word in a sentence (for example, “Four score and seven years ago” results in a password of “Fsasya”). The
password is easy to remember and type, but difficult to guess for someone who does not know the sentence. In this case, you can additionally substitute
digits for the number words to obtain the phrase “4 score and 7 years ago”, yielding the password “4sa7ya” which is even more difficult to guess.
Invest in a firewall. This protects you from at least 50% of all types of exploits in any software. Put MySQL behind the firewall or in a demilitarized zone
(DMZ).
Checklist:
o Try to scan your ports from the Internet using a tool such as nmap. MySQL uses port 3306 by default. This port should not be accessible from
untrusted hosts. As a simple way to check whether your MySQL port is open, try the following command from some remote machine,
where server_host is the host name or IP address of the host on which your MySQL server runs:
If telnet hangs or the connection is refused, the port is blocked, which is how you want it to be. If you get a connection and some garbage characters, the port is
open, and should be closed on your firewall or router, unless you really have a good reason to keep it open.
Applications that access MySQL should not trust any data entered by users, and should be written using proper defensive programming techniques.
See Section 6.1.7, “Client Programming Security Guidelines” .
Do not transmit plain (unencrypted) data over the Internet. This information is accessible to everyone who has the time and ability to intercept it and
use it for their own purposes. Instead, use an encrypted protocol such as SSL or SSH. MySQL supports internal SSL connections. Another technique is to
use SSH port-forwarding to create an encrypted (and compressed) tunnel for the communication.
Learn to use the tcpdump and strings utilities. In most cases, you can check whether MySQL data streams are unencrypted by issuing a command like
the following:
This works under Linux and should work with small modifications under other systems.
To install Apache with PHP 5 on Windows follow the following steps. If your PHP and Apache versions are different then please take care accordingly.
Download Apache server from www.apache.org/dist/httpd/binaries/win32. You want the current stable release version with the no_src.msi extension.
Double-click the installer file to install; C:\Program Files is a common location. The installer will also ask you whether you want to run Apache as a service
or from the command line or DOS prompt. We recommend you do not install as a service, as this may cause problems with startup.
Extract the PHP binary archive using your unzip utility; C:\PHP is a common location.
Copy some .dll files from your PHP directory to your system directory (usually C:\Windows). You need php5ts.dll for every case. You will also probably
need to copy the file corresponding to your Web server module - C:\PHP\Sapi\php5apache.dll. to your Apache modules directory. It's possible that you
will also need others from the dlls subfolder.but start with the two mentioned previously and add more if you need them.
Copy either php.ini-dist or php.ini-recommended (preferably the latter) to your Windows directory, and rename it php.ini. Open this file in a text editor
(for example, Notepad). Edit this file to get configuration directives; At this point, we highly recommend that new users set error reporting to E_ALL on
their development machines.
Tell your Apache server where you want to serve files from and what extension(s) you want to identify PHP files (.php is the standard, but you can use
.html, .phtml, or whatever you want). Go to your HTTP configuration files (C:\Program Files\Apache Group\Apache\conf or whatever your path is), and
open httpd.conf with a text editor. Search for the word DocumentRoot (which should appear twice) and change both paths to the directory you want to
serve files out of. (The default is C:\Program Files\Apache Group\Apache\htdocs.). Add at least one PHP extension directive as shown in the first line of
the following code −
AddModule mod_php5.c
Stop and restart the WWW service. Go to the Start menu → Settings → Control Panel → Services. Scroll down the list to IIS Admin Service. Select it and
click Stop. After it stops, select World Wide Web Publishing Service and click Start. Stopping and restarting the service from within Internet Service
Manager will not suffice. Since this is Windows, you may also wish to reboot.
Open a text editor. Type: <?php phpinfo(); ?>. Save this file in your Web server's document root as info.php.
Start any Web browser and browse the file.you must always use an HTTP request (http://www.testdomain.com/info.php or http://localhost/info.php or
http://127.0.0.1/info.php) rather than a filename (/home/httpd/info.php) for the file to be parsed correctly
You should see a long table of information about your new PHP installation message Congratulations!
PHP.ini
The php.ini file is the default configuration file for running applications that require PHP. It is used to control variables such as upload sizes, file timeouts, and
resource limits.
At the time of PHP installation, php.ini is a special file provided as a default configuration file. It’s very essential configuration file which controls, what a user can
or cannot do with the website. Each time PHP is initialized, the php.ini file is read by the system. Sometimes you need to change the behavior of PHP at runtime,
then this configuration file is to use.
All the settings related to register global variables, upload maximum size, display log errors, resource limits, the maximum time to execute a PHP script and
others are written in a file as a set of directives which helps in declaring changes.
The configuration file is well commented and thorough. Keys are case sensitive, keyword values are not; whitespace, and lines beginning with semicolons are
ignored. Booleans can be represented by 1/0, Yes/No, On/Off, or True/False. The default values in php.ini-dist will result in a reasonable PHP installation that can
be tweaked later.
Configuration of php.ini file: Whenever we install PHP, we can locate the configuration file inside the PHP folder. If using xampp, we can find the configuration
file in one or many versions, inside the path ‘\xampp\php’.
1. enable_safe_mode = on Its default setting to ON whenever PHP is compiled. Safe mode is most relevant to CGI use.
2. register_globals = on its default setting to ON which tells that the contents of EGPCS (Environment, GET, POST, Cookie, Server) variables are registered
as global variables. But due to a security risk, the user has to ensure if it set to OFF for all scripts.
3. upload_max_filesize This setting is for the maximum allowed size for uploaded files in the scripts.
5. post_max_size This setting is for the maximum allowed size of POST data that PHP will accept.
6. display_errors = off This setting will not allow showing errors while running PHP project in the specified host.
7. error_reporting = E_ALL & ~E_NOTICE: This setting has default values as E_ALL and ~E_NOTICE which shows all errors except notices.
8. error_prepend_string = [“”] This setting allow you to make different color of messages.
9. max_execution_time = 30 Maximum execution time is set to seconds for any script to limit the time in production servers.
10. short_open_tags = Off To use XML functions, we have to set this option as off.
12. variables_order = EGPCS This setting is done to set the order of variables as Environment, GET, POST, COOKIE, SERVER. The developer can change the
order as per the need also.
13. warn_plus_overloading = Off This setting issues a warning if + used with strings in a form of value.
15. magic_quotes_gpc = on This setting is done in case of many forms are used which submits to themselves or others and display form values.
16. magic_quotes_runtime = Off If magic_quotes_sybase is set to On, this must be Off, this setting escape quotes.
17. magic_quotes_sybase = Off If this setting is set to off it should be off, this setting escape quotes.
18. auto-prepend-file = [filepath] This setting is done when we need to automatically include() it at the beginning of every PHP file.
19. auto-append-file = [filepath] This setting is done when we need to automatically include() it at the end of every PHP file.
20. include_path = [DIR] This setting is done when we need to require files from the specified directories. Multiple directories are set using colons.
21. ignore_user_abort = [On/Off] This settings control what will happen when the user click any stop button. The default value is on this setting doesn’t
work on CGI mode it works on only module mode.
22. doc_root = [DIR] This setting is done if we want to apply PHP to a portion of our website.
23. file_uploads = [on/off] This flag is set to ON if file uploads are included in the PHP code.
24. mysql.default_host = hostname This setting is done to connect to MySQL default server if no other server host is mentioned.
25. mysql.default_user = username This setting is done to connect MySQL default username, if no other name is mentioned.
26. mysql.default_password = password This setting is done to connect MySQL default password if no other password is mentioned.
Basics of PHP
PHP or Hypertext Preprocessor is a widely used open-source general purpose scripting language and can be embedded with HTML. PHP files are saved with
“.php” extension. PHP scripts can be written anywhere in the document within PHP tags along with normal HTML.
The mechanism of separating a normal HTML from PHP code is called the mechanism of Escaping To PHP. There are various ways in which this can be done. Few
methods are already set by default but in order to use few others like Short-open or ASP-style tags we need to change the configuration of php.ini file. These
tags are also used for embedding PHP within HTML. There are 4 such tags available for this purpose:-
1. Canonical PHP Tags:The script starts with <?php and ends with ?> . These tags are also called ‘Canonical PHP tags’. Every PHP command ends with a
semi-colon (;). Let’s look at the hello world program in PHP:
<?php
?>
Output:
Hello, world!
2. SGML or Short HTML Tags: These are the shortest option to initialize a PHP code. The script starts with <? and ends with ?>. This will only work by
setting the short_open_tag setting in php.ini file to ‘on’.
Example:
<?
?>
3. HTML Script Tags: These are implemented using script tags. This syntax is removed in PHP 7.0.0. so its no more used.
Example:
<script language="php">
</script>
4. ASP Style Tags: To use this we need to set the configuration of php.ini file. These are used by Active Server Pages to describe code blocks. These starts
with <% and ends with %>.
Example:
<%
# to allow %
%>
Comments in PHP
A comment is something which is ignored and not read or executed by PHP engine or the language as part of a program and is written to make the code more
readable and understandable. These are used to help other users and developers to describe the code and what it is trying to do. It can also be used in
documenting a set of code or part of a program. You must have noticed this in above sample programs.
PHP supports two types of comment:
Single Line Comment: As the name suggests these are single line or short relevant explanations that one can add in there code. To add this, we need to
begin the line with (//) or (#).
Example:
<?php
?>
Output:
hello world!!!
Multi-line or Multiple line Comment: These are used to accomodate multiple lines with a single tag and can be extended to many lines as required by
the user. To add this, we need to begin and end the line with (/*…*/)
<?php
echo $geek;
?>
Output:
hello world!
PHP is insensitive of whitespace. This includes all types of spaces that are invisible on the screen including tabs, spaces, and carriage return. Even one space is
equal to any numbers of spaces or carriage return. This means that PHP will ignore all the spaces or tabs in a single row or carriage return in multiple rows.
Unless a semi-colon is encountered, PHP treats multiple lines as a single command.
Example:
<?php
// PHP code illustrate the whitespace insensitivity
$var1 = 15;
$var2 =
30;
$sum = $var1
+
$var2;
// "\n" for new line
echo $sum, "\n";
$sum1 = $var1 + $var2;
echo $sum1;
?>
Output:
45
45
PHP is case-sensitive. All the keywords, functions and class names in PHP (while, if, echo etc) are NOT case-sensitive except variables. Only variables with
different cases are treated differently. Let’s look at this example:
<?php
$variable = 25;
echo $variable;
ECHO $variable;
EcHo $variable;
// "Undefined Variable"
echo $VARIABLE
?>
Output:
25
25
25
Blocks in PHP
In PHP, multiple statements can be executed simultaneously (under a single condition or loop) by using curly-braces ({}). This forms a block of statements which
gets executed simultaneously.
<?php
$var = 50;
if ($var>0){
?>
Output:
Positive as
greater than 0
PHP Script
The PHP delimiter <?php and ?> in the following example simply tells the PHP engine to treat the enclosed code block as PHP code, rather than simple HTML.
Example
<?php
?>
Every PHP statement end with a semicolon (;) — this tells the PHP engine that the end of the current statement has been reached.
Building Block of PHP
Variables:-
Variables in a program are used to store some values or data that can be used later in a program. PHP has its own way of declaring
and storing variables.
There are few rules, that needs to be followed and facts that need to be kept in mind while dealing with variables in PHP:
Any variables declared in PHP must begin with a dollar sign ($), followed by the variable name.
A variable can have long descriptive names (like $factorial, $even_nos) or short names (like $n or $f or $x)
A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’, ‘A-Z’, ‘0-9 and ‘_’) in their name.
Assignment of variables are done with assignment operator, “equal to (=)”. The variable names are on the left of equal and the
expression or values are to the right of the assignment operator ‘=’.
One must keep in mind that variable names in PHP names must start with a letter or underscore and no numbers.
PHP is a loosely typed language and we do not require to declare the data types of variables, rather PHP assumes it
automatically by analyzing the values. Same happens while conversion.
PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.
$variablename=value;
← prev
1. Local variable
2. Global variable
3. Static variable
Local variable
The variables that are declared within a function are called local variables for that function. These local variables have their scope only in that
particular function in which they are declared. This means that these variables cannot be accessed outside the function, as they have local
scope.
A variable declaration outside the function with the same name is completely different from the variable declared inside the function. Let's
understand the local variables with the help of an example:
File: local_variable1.php
1. <?php
2. function local_var()
3. {
4. $num = 45; //local variable
5. echo "Local variable declared inside the function is: ". $num;
6. }
7. local_var();
8. ?>
Output:
File: local_variable2.php
1. <?php
2. function mytest()
3. {
4. $lang = "PHP";
5. echo "Web development language: " .$lang;
6. }
7. mytest();
8. //using $lang (local variable) outside the function will generate an error
9. echo $lang;
10. ?>
Output:
Global variable
The global variables are the variables that are declared outside the function. These variables can be accessed anywhere in the program. To
access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed
or used outside the function without any keyword. Therefore there is no need to use any keyword to access a global variable outside the
function.
Example:
File: global_variable1.php
1. <?php
2. $name = "Sanaya Sharma"; //Global Variable
3. function global_var()
4. {
5. global $name;
6. echo "Variable inside the function: ". $name;
7. echo "</br>";
8. }
9. global_var();
10. echo "Variable outside the function: ". $name;
11. ?>
Output:
Note: Without using the global keyword, if you try to access a global variable inside the function, it will generate an error that the
variable is undefined.
Example:
File: global_variable2.php
1. <?php
2. $name = "Sanaya Sharma"; //global variable
3. function global_var()
4. {
5. echo "Variable inside the function: ". $name;
6. echo "</br>";
7. }
8. global_var();
9. ?>
Output:
Example:
File: global_variable3.php
1. <?php
2. $num1 = 5; //global variable
3. $num2 = 13; //global variable
4. function global_var()
5. {
6. $sum = $GLOBALS['num1'] + $GLOBALS['num2'];
7. echo "Sum of global variables is: " .$sum;
8. }
9. global_var();
10. ?>
Output:
If two variables, local and global, have the same name, then the local variable has higher priority than the global variable inside the function.
Example:
File: global_variable2.php
1. <?php
2. $x = 5;
3. function mytest()
4. {
5. $x = 7;
6. echo "value of x: " .$x;
7. }
8. mytest();
9. ?>
Output:
Value of x: 7
Note: local variable has higher priority than the global variable.
Static variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed. Sometimes we need to store a variable even
after completion of function execution. Therefore, another important feature of variable scoping is static variable. We use the static keyword
before the variable to define a variable, and this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program execution leaves the scope. Understand it with
the help of an example:
Example:
File: static_variable.php
1. <?php
2. function static_var()
3. {
4. static $num1 = 3; //static variable
5. $num2 = 6; //Non-static variable
6. //increment in non-static variable
7. $num1++;
8. //increment in static variable
9. $num2++;
10. echo "Static: " .$num1 ."</br>";
11. echo "Non-static: " .$num2 ."</br>";
12. }
13.
14. //first function call
15. static_var();
16.
17. //second function call
18. static_var();
19. ?>
Output:
Static: 4
Non-static: 7
Static: 5
Non-static: 7
You have to notice that $num1 regularly increments after each function call, whereas $num2 does not. This is why because $num1 is not a
static variable, so it freed its memory after the execution of each function call
Data Types
1. boolean
2. integer
3. float
4. string
1. array
2. object
1. resource
2. NULL
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is often used with conditional
statements. If the condition is correct, it returns TRUE otherwise FALSE.
Example:
1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>
Output:
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers without fractional part or decimal
points.
Example:
1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional or decimal point, including a
negative or positive sign.
Example:
1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters.
String values must be enclosed either within single quotes or in double quotes. But both are treated differently. To clarify this, see the
example below:
Example:
1. <?php
2. $company = "Javatpoint";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
6. echo 'Hello $company';
7. ?>
Output:
Hello Javatpoint
Hello $company
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and values
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
You will learn more about array in later chapters of this tutorial.
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly declared.
Example:
1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references to external PHP
resources. For example - a database call. It is an external resource.
This is an advanced topic of PHP, so we will discuss it later in detail with examples.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
1. <?php
2. $nl = NULL;
3. echo $nl; //it will not give any output
4. ?>
Output:
Operators
HP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to perform operations on variables
or values. For example:
1. $num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition, subtraction, etc. with numeric values.
Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment operator is "=".
Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators allow the evaluation and manipulation of specific
bits within the integer.
& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.
| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison operators are given:
=== Identical $a === Return TRUE if $a is equal to $b, and they are of same data type
$b
!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not of same
data type
<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b
>= Greater than or equal $a >= $b Return TRUE if $a is greater than or equal $b
to
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.
Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the evaluation and manipulation of specific
bits within the integer.
xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
String Operators
The string operators are used to perform the operation on strings. There are two string operators in PHP, which are given below:
.= Concatenation and $a .= First concatenate $a and $b, then assign the concatenated string
Assignment $b to $a, e.g. $a = $a . $b
Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the values of arrays.
=== Identity $a === Return TRUE if $a and $b have same key/value pair of same type in same
$b order
Type Operators
The type operator instanceof is used to determine whether an object, its parent and its derived class are the same type or not. Basically,
this operator determines which certain class the object belongs to. It is used in object-oriented programming.
1. <?php
2. //class declaration
3. class Developer
4. {}
5. class Programmer
6. {}
7. //creating an object of type Developer
8. $charu = new Developer();
9.
10. //testing the type of object
11. if( $charu instanceof Developer)
12. {
13. echo "Charu is a developer.";
14. }
15. else
16. {
17. echo "Charu is a programmer.";
18. }
19. echo "</br>";
20. var_dump($charu instanceof Developer); //It will return true.
21. var_dump($charu instanceof Programmer); //It will return false.
22. ?>
Output:
Charu is a developer.
bool(true) bool(false)
Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell command. Execution operator
and shell_exec() give the same result.
`` backticks echo `dir`; Execute the shell command and return the result.
Here, it will show the directories available in current folder.
[ array() left
** arithmetic right
++ -- ~ (int) (float) (string) (array) (object) (bool) @ increment/decrement and types right
| bitwise OR left
|| logical OR left
?: ternary left
or logical left
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the script except for magic constants, which are not really
constants. PHP constants can be defined by 2 ways:
Constants are similar to the variable except once they defined, they can never be undefined or changed. They remain constant across the
entire program. PHP constants follow the same PHP variable rules. For example, it can be started with a letter or underscore only.
Note: Unlike variables, constants are automatically global throughout the script.
1. define(name, value, case-insensitive)
1. name: It specifies the constant name.
2. value: It specifies the constant value.
3. case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It means it is case sensitive by default.
File: constant1.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>
Output:
File: constant2.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE, "</br>";
4. echo message;
5. ?>
Output:
File: constant3.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>
Output:
File: constant4.php
1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>
Output:
Constant() function
There is another way to print the value of constants using constant() function instead of using the echo statement.
Syntax
1. constant (name)
File: constant5.php
1. <?php
2. define("MSG", "JavaTpoint");
3. echo MSG, "</br>";
4. echo constant("MSG");
5. //both are similar
6. ?>
Output:
JavaTpoint
JavaTpoint
Constant vs Variables
Constant Variables
Once the constant is defined, it can never be redefined. A variable can be undefined as well as redefined easily.
A constant can only be defined using define() function. It A variable can be defined by simple assignment (=)
cannot be defined by any simple assignment. operator.
There is no need to use the dollar ($) sign before constant To declare a variable, always use the dollar ($) sign
during the assignment. before the variable.
Constants do not follow any variable scoping rules, and they Variables can be declared anywhere in the program,
can be defined and accessed anywhere. but they follow variable scoping rules.
Constants are the variables whose values can't be changed The value of the variable can be changed.
throughout the program.
Switching Flow:-
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.
Syntax
1. switch(expression){
2. case value1:
3. //code to be executed
4. break;
5. case value2:
6. //code to be executed
7. break;
8. ......
9. default:
10. code to be executed if all cases are not matched;
11. }
Important points to be noticed about switch case:
1. The default is an optional statement. Even it is not important, that default must always be the last statement.
2. There can be only one default in a switch statement. More than one default may lead to a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of statement.
4. The break statement is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and less readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.
PHP Switch Flowchart
Output:
number is equal to 20
We will pass a character in switch expression to check whether it is vowel or constant. If the passed character is A, E, I, O, or U, it will be
vowel otherwise consonant.
1. <?php
2. $ch = 'U';
3. switch ($ch)
4. {
5. case 'a':
6. echo "Given character is vowel";
7. break;
8. case 'e':
9. echo "Given character is vowel";
10. break;
11. case 'i':
12. echo "Given character is vowel";
13. break;
14. case 'o':
15. echo "Given character is vowel";
16. break;
17. case 'u':
18. echo "Given character is vowel";
19. break;
20. case 'A':
21. echo "Given character is vowel";
22. break;
23. case 'E':
24. echo "Given character is vowel";
25. break;
26. case 'I':
27. echo "Given character is vowel";
28. break;
29. case 'O':
30. echo "Given character is vowel";
31. break;
32. case 'U':
33. echo "Given character is vowel";
34. break;
35. default:
36. echo "Given character is consonant";
37. break;
38. }
39. ?>
Output:
1. <?php
2. $ch = "B.Tech";
3. switch ($ch)
4. {
5. case "BCA":
6. echo "BCA is 3 years course";
7. break;
8. case "Bsc":
9. echo "Bsc is 3 years course";
10. break;
11. case "B.Tech":
12. echo "B.Tech is 4 years course";
13. break;
14. case "B.Arch":
15. echo "B.Arch is 5 years course";
16. break;
17. default:
18. echo "Wrong Choice";
19. break;
20. }
21. ?>
Output:
1. <?php
2. $ch = 'c';
3. switch ($ch)
4. {
5. case 'a':
6. echo "Choice a";
7. break;
8. case 'b':
9. echo "Choice b";
10. break;
11. case 'c':
12. echo "Choice c";
13. echo "</br>";
14. case 'd':
15. echo "Choice d";
16. echo "</br>";
17. default:
18. echo "case a, b, c, and d is not found";
19. }
20. ?>
Output:
Choice c
Choice d
case a, b, c, and d is not found
1. <?php
2. $car = "Hyundai";
3. $model = "Tucson";
4. switch( $car )
5. {
6. case "Honda":
7. switch( $model )
8. {
9. case "Amaze":
10. echo "Honda Amaze price is 5.93 - 9.79 Lakh.";
11. break;
12. case "City":
13. echo "Honda City price is 9.91 - 14.31 Lakh.";
14. break;
15. }
16. break;
17. case "Renault":
18. switch( $model )
19. {
20. case "Duster":
21. echo "Renault Duster price is 9.15 - 14.83 L.";
22. break;
23. case "Kwid":
24. echo "Renault Kwid price is 3.15 - 5.44 L.";
25. break;
26. }
27. break;
28. case "Hyundai":
29. switch( $model )
30. {
31. case "Creta":
32. echo "Hyundai Creta price is 11.42 - 18.73 L.";
33. break;
34. case "Tucson":
35. echo "Hyundai Tucson price is 22.39 - 32.07 L.";
36. break;
37. case "Xcent":
38. echo "Hyundai Xcent price is 6.5 - 10.05 L.";
39. break;
40. }
41. break;
42. }
43. ?>
Output:
It should be used if the number of iterations is known otherwise use while loop. This means for loop is used when you already know how
many times you want to execute a block of code.
It allows users to put all the loop related statements in one place. See in the syntax given below:
Syntax
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }
Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the following meanings:
initialization - Initialize the loop counter value. The initial value of the for loop is done only once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the condition is false. If TRUE, the loop execution continues,
otherwise the execution of the loop ends.
Flowchart
Example
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
Output:
1
2
3
4
5
6
7
8
9
10
Example
All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't pass parameters, it will execute infinite.
1. <?php
2. $i = 1;
3. //infinite loop
4. for (;;) {
5. echo $i++;
6. echo "</br>";
7. }
8. ?>
Output:
1
2
3
4
.
.
.
Example
Below is the example of printing numbers from 1 to 9 in four different ways using for loop.
1. <?php
2. /* example 1 */
3.
4. for ($i = 1; $i <= 9; $i++) {
5. echo $i;
6. }
7. echo "</br>";
8.
9. /* example 2 */
10.
11. for ($i = 1; ; $i++) {
12. if ($i > 9) {
13. break;
14. }
15. echo $i;
16. }
17. echo "</br>";
18.
19. /* example 3 */
20.
21. $i = 1;
22. for (; ; ) {
23. if ($i > 9) {
24. break;
25. }
26. echo $i;
27. $i++;
28. }
29. echo "</br>";
30.
31. /* example 4 */
32.
33. for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);
34. ?>
Output:
123456789
123456789
123456789
123456789
In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is to be executed for 3 times and
inner for loop for 3 times, inner for loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd
outer loop).
Example
1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. }
6. }
7. ?>
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Syntax
1. foreach( $array as $var ){
2. //code to be executed
3. }
4. ?>
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
Output:
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an array.
Syntax
1. foreach ($array as $value) {
2. //code to be executed
3. }
Syntax
1. foreach ($array as $key => $element) {
2. //code to be executed
3. }
Flowchart
Example 1:
PHP program to print array elements using foreach loop.
1. <?php
2. //declare array
3. $season = array ("Summer", "Winter", "Autumn", "Rainy");
4.
5. //access array elements using foreach loop
6. foreach ($season as $element) {
7. echo "$element";
8. echo "</br>";
9. }
10. ?>
Output:
Summer
Winter
Autumn
Rainy
Example 2:
PHP program to print associative array elements using foreach loop.
1. <?php
2. //declare array
3. $employee = array (
4. "Name" => "Alex",
5. "Email" => "alex_jtp@gmail.com",
6. "Age" => 21,
7. "Gender" => "Male"
8. );
9.
10. //display associative array element through foreach loop
11. foreach ($employee as $key => $element) {
12. echo $key . " : " . $element;
13. echo "</br>";
14. }
15. ?>
Output:
Name : Alex
Email : alex_jtp@gmail.com
Age : 21
Gender : Male
Example 3:
Multi-dimensional array
1. <?php
2. //declare multi-dimensional array
3. $a = array();
4. $a[0][0] = "Alex";
5. $a[0][1] = "Bob";
6. $a[1][0] = "Camila";
7. $a[1][1] = "Denial";
8.
9. //display multi-dimensional array elements through foreach loop
10. foreach ($a as $e1) {
11. foreach ($e1 as $e2) {
12. echo "$e2\n";
13. }
14. }
15. ?>
Output:
Example 4:
Dynamic array
1. <?php
2. //dynamic array
3. foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) {
4. echo "$elements\n";
5. }
6. ?>
Output:
j a v a t p o i n t
The while loop is also called an Entry control loop because the condition is checked before entering the loop body. This means that first the
condition is checked. If the condition is true, the block of code will be executed.
Syntax
1. while(condition){
2. //code to be executed
3. }
Alternative Syntax
1. while(condition):
2. //code to be executed
3.
4. endwhile;
PHP While Loop Flowchart
Output:
1
2
3
4
5
6
7
8
9
10
Alternative Example
1. <?php
2. $n=1;
3. while($n<=10):
4. echo "$n<br/>";
5. $n++;
6. endwhile;
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
Example
Below is the example of printing alphabets using while loop.
1. <?php
2. $i = 'A';
3. while ($i < 'H') {
4. echo $i;
5. $i++;
6. echo "</br>";
7. }
8. ?>
Output:
A
B
C
D
E
F
G
In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer while loop is to be executed for 3
times and nested while loop for 3 times, nested while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and
3 times for 3rd outer loop).
Example
1. <?php
2. $i=1;
3. while($i<=3){
4. $j=1;
5. while($j<=3){
6. echo "$i $j<br/>";
7. $j++;
8. }
9. $i++;
10. }
11. ?>
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Syntax
1. while(true) {
2. //code to be executed
3. }
Example
1. <?php
2. while (true) {
3. echo "Hello Javatpoint!";
4. echo "</br>";
5. }
6. ?>
Output:
Hello Javatpoint!
Hello Javatpoint!
Hello Javatpoint!
Hello Javatpoint!
.
.
.
.
.
Hello Javatpoint!
Hello Javatpoint!
The PHP do-while loop is used to execute a set of code of the program several times. If you have to execute the loop at least once and the
number of iterations is not even fixed, it is recommended to use the do-while loop.
It executes the code at least one time always because the condition is checked after executing the code.
The do-while loop is very much similar to the while loop except the condition check. The main difference between both loops is that while loop
checks the condition at the beginning, whereas do-while loop checks the condition at the end of the loop.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
Flowchart
Example
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
Example
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-while loop, it is must that the program should
not contain any other statements after the do-while loop. In this case, it will not generate any error.
1. <?php
2. $x = 5;
3. do {
4. echo "Welcome to javatpoint! </br>";
5. $x++;
6. } while ($x < 10);
7. ?>
Output:
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Example
The following example will increment the value of $x at least once. Because the given condition is false.
1. <?php
2. $x = 1;
3. do {
4. echo "1 is not greater than 10.";
5. echo "</br>";
6. $x++;
7. } while ($x > 10);
8. echo $x;
9. ?>
Output:
The while loop is also named as entry control loop. The do-while loop is also named as exit control loop.
The body of the loop does not execute if the condition The body of the loop executes at least once, even if the
is false. condition is false.
Condition checks first, and then block of statements Block of statements executes first and then condition checks.
executes.
This loop does not use a semicolon to terminate the Do-while loop use semicolon to terminate the loop.
loop.
CHAPTER 2
Basic Working
Functions:-
What is Function?
A function is a block of code written in a program to perform some specific task. We can relate functions in programs to employees in a office in real life
for a better understanding of how functions work. Suppose the boss wants his employee to calculate the annual budget. So how will this process
complete? The employee will take information about the statics from the boss, performs calculations and calculate the budget and shows the result to
his boss. Functions works in a similar manner. They take informations as parameter, executes a block of statements or perform operations on this
parameters and returns the result.
We can declare and call user-defined functions easily. Let's see the syntax to declare user-defined functions.
Syntax
1. function functionname(){
2. //code to be executed
3. }
Note: Function name must be start with letter and underscore only like other labels in PHP. It can't be start with numbers or special
symbols.
1. <?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>
Output:
File: functionarg.php
1. <?php
2. function sayHello($name){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Sonoo");
6. sayHello("Vimal");
7. sayHello("John");
8. ?>
Output:
Hello Sonoo
Hello Vimal
Hello John
1. <?php
2. function sayHello($name,$age){
3. echo "Hello $name, you are $age years old<br/>";
4. }
5. sayHello("Sonoo",27);
6. sayHello("Vimal",29);
7. sayHello("John",23);
8. ?>
Output:
By default, value passed to the function is call by value. To pass value as a reference, you need to use ampersand (&) symbol before the
argument name.
File: functionref.php
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>
Output:
File: functiondefaultarg.php
1. <?php
2. function sayHello($name="Sonoo"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Rajesh");
6. sayHello();//passing no value
7. sayHello("John");
8. ?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
File: functiondefaultarg.php
1. <?php
2. function cube($n){
3. return $n*$n*$n;
4. }
5. echo "Cube of 3 is: ".cube(3);
6. ?>
Output:
Cube of 3 is: 27
Array
What is Array?
Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving
us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be
accessed using their index or key. Suppose we want to store five names and print them accordingly. This can be easily done by the use of five
different string variables. But if instead of five, the number rises to hundred, then it would be really difficult for the user or developer to
create so much different variables. Here array comes into play and helps us to store every element within a single variable and also allows
easy access using an index or a key. An array is created using an array() function in PHP.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
File: array2.php
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>
Output:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>
Output:
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
File: multiarray.php
1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14. }
15. ?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
Syntax
1. array array ([ mixed $... ] )
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
Syntax
1. array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>
Output:
Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )
1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>
Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
Syntax
1. int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>
Output:
Syntax
1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
summer
winter
Syntax
1. array array_reverse ( array $array [, bool $preserve_keys = false ] )
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
winter
summer
Syntax
1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>
Output:
Syntax
1. array array_intersect ( array $array1 , array $array2 [, array $... ] )
Example
1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>
Output:
sonoo
smith
Object
PHP | Objects
An Object is an individual instance of the data structure defined by a class. We define a class once and then make many objects that belong to it. Objects are also
known as instances.
Creating an Object:
Following is an example of how to create object using new operator.
class Books {
Member Functions:
After creating our objects, we can call member functions related to that object. A member function typically accesses members of current object only.
Example:
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
The following syntax used are for the following program elaborated in the example given below:
Example:
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price."<br>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title."<br>" ;
}
}
/* Creating New object using "new" operator */
$maths = new Books;
/* Setting title and prices for the object */
$maths->setTitle( "Algebra" );
$maths->setPrice( 7 );
/* Calling Member Functions */
$maths->getTitle();
$maths->getPrice();
?>
We can achieve this conversion by using strtotime() and date() function. These are the built-in functions of PHP. The strtotime() first converts
the date into the seconds, and then date() function is used to reconstruct the date in any format. Below some examples are given to convert
the date format.
1. <?php
2. $orgDate = "2019-09-15";
3. $newDate = date("d-m-Y", strtotime($orgDate));
4. echo "New date format is: ".$newDate. " (MM-DD-YYYY)";
5. ?>
Output
New date format is: 15-09-2019 (DD-MM-YYYY)
1. <?php
2. $orgDate = "2019-02-26";
3. $newDate = date("m-d-Y", strtotime($orgDate));
4. echo "New date format is: ".$newDate. " (MM-DD-YYYY)";
5. ?>
Output
1. <?php
2. $orgDate = "17-07-2012";
3. $newDate = date("Y-m-d", strtotime($orgDate));
4. echo "New date format is: ".$newDate. " (YYYY-MM-DD)";
5. ?>
Output
1. <?php
2. $orgDate = "17-07-2012";
3. $date = str_replace('-"', '/', $orgDate);
4. $newDate = date("Y/m/d", strtotime($date));
5. echo "New date format is: ".$newDate. " (YYYY/MM/DD)";
6. ?>
Output
1. <?php
2. $date = "06/13/2019 5:35 PM";
3. //converts date and time to seconds
4. $sec = strtotime($date);
5. //converts seconds into a specific format
6. $newdate = date ("Y/d/m H:i", $sec);
7. //Appends seconds with the time
8. $newdate = $newdate . ":00";
9. // display converted date and time
10. echo "New date time format is: ".$newDate;
11. ?>
Output
strlen($str)
This function returns the length of the string or the number of characters in the string including whitespaces.
<?php
?>
str_word_count($str)
This function returns the number of words in the string. This function comes in handly in form field validation for some simple
validations.
<?php
?>
strrev($str)
This function is used to reverse a string.
Let's take an example and see,
<?php
?>
strpos($str, $text)
This function is used to find the position of any text/word in a given string. Just like an array, string also assign index value to the
characters stored in it, starting from zero.
<?php
?>
echo $str;
?>
Welcome to Studytonight.com
ucwords($str)
This function is used for formatting the string. This function converts first letter/character of every word in the string to uppercase.
Let's take an example and see,
<?php
echo ucwords($str);
?>
Welcome To Studytonight
strtoupper($str)
To convert every letter/character of every word of the string to uppercase, one can use strtoupper() method.
<?php
echo strtoupper($str);
?>
WELCOME TO STUDYTONIGHT
strtolower($str)
This function is used to convert every letter/character of a string to lowercase.
<?php
echo strtolower($str);
?>
welcome to studytonight
str_repeat($str, $counter)
This function is used to repeat a string a given number of times. The first argument is the string and the second argument is the number
of times the string should be repeated.
<?php
$str = "Studytonight";
?>
StudytonightStudytonightStudytonightStudytonight
strcmp($str1, $str2)
This function is used to compare two strings. The comparison is done alphabetically. If the first string is greater than second string, the
result will be greater than 0, if the first string is equal to the second string, the result will be equal to 0 and if the second string is greater
than the first string, then the result will be less than 0.
<?php
$str1 = "Studytonight";
$str2 = "Studytonight.com";
?>
-4
0
substr($str, $start, $length)
This function is used to take out a part of the string(substring), starting from a particular position, of a particular length.
The first argument is the string itself, second argument is the starting index of the substring to be exracted and the third argument is the
length of the substring to be extracted.
<?php
?>
Studytonight
trim($str, charlist)
This function is used to remove extra whitespaces from beginning and the end of a string. The second argument charlist is optional.
We can provide a list of character, just like a string, as the second argument, to trim/remove those characters from the main string.
<?php
echo trim($str2,"Heo");
?>
Hello World
llo Hell
As you can see in the output, additional spaces from the beginning and end are removed and in the second case, the characters
specified are removed from the beginning and the end of the string.
?>
Array (
[0] => Its
[1] => a
In the example above, we have provided space as separator to break the string and return an array.
If we provide the third argument limit as well, we can limit the number of array elements returned. For example, if we provide 2 as the
third argument, then we will only get 2 elements in the array, the first two.
implode(separator, $arr)
This function is used to form a string using the array elements from the array provided and join them using the separator.
Let's take an example,
<?php
?>
Its-a-beautiful-day
Its/a/beautiful/day
nl2br($str)
This function is used to change line break or \n to the HTML tag for line break, which is <br>.
This function is very useful to format string data to display on HTML pages because when a multiline form data is submitted, it
has \n included in the strnig for line breaks, but when you display it on your HTML page, the line breaks will not get rendered because
HTML doesn't understand \n.
<?php
?>
Its a
beautiful day
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<p>username <input type="text" name="usser"/></p>
<p>password <input type="password" name="pass" /></p>
<p> <input type="submit" name="submit" /></p>
</form>
<?php
$name = $_REQUEST['usser'];
$pas=$_REQUEST['pass'];
if($name=="mandeep"&&$pas=="mani"){
echo "successful";
}
else{
echo "Login Failed";
}
?>
</body>
</html>
<body>
<input type="submit">
</form>
</body>
</html>
In the code above, we have used the <form> tag to create an HTML form, with input fields for Name and Email along with submit button
to submit the form-data.
In the <form> tag, we have two attributes, action and method, do you know what they are for?
1. action: Using this attribute, we can specify the name of the file which will collect and handle the form-data. In the example above, we have
2. method: This attribute specify the means of sending the form-data, whether it will be submitted via POST method or GET method.
<body>
<input type="submit">
</form>
</body>
</html>
$email = $_POST["email"];
?>
Hi, Studytonight
You will get the above output, if you provide name as "Studytonight" and email address as "we@studytonight.com".
$name = $_GET["name"];
$email = $_GET["email"];
?>
Hi, Studytonight
<body>
<input type="submit">
</form>
</body>
</html>
We have two input fields in above form, one is name and the other one is age. When we click on submit, we will be redicrected to the
following URL, form-handler.php?name=Studytonight&age=5, with the form-data appended to the URL.
Sending the form-data as URL parameters proves out useful at times as you can easily bookmark links with form-data, but for
appending parameters in a URL there is a limit of 2000 characters, hence for forms with large number of fields, it is not suggested, as
some data might get lost or the form submission may lead to error.
The Php file form-handler.php will look like,
<?php
$name = $_GET["name"];
$age = $_GET["age"];
echo "Your name is ". $name . " and you are ". $age . " years old".
?>
As the form-data is visible to everyone because it sent as URL parameters, hence we should not use GET method for a form
with sensitive data, like passwords etc.
<body>
<form action="form-handler.php" method="POST">
<input type="submit">
</form>
</body>
</html>
$name = $_POST["name"];
$age = $_POST["age"];
echo "Your name is ". $name . " and you are ". $age . " years old".
?>