PHP Total PDF
PHP Total PDF
PHP
PHP stands for " Hypertext Preprocessor".
PHP scripts are executed on the server so it is a server side scripting language that is
embedded in HTML.
PHP is a widely-used, open source scripting language , is free to download and use.
It is integrated with a number of popular databases, including MySQL, Oracle, Microsoft
SQL Server…etc.
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP files have extension " .php "
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:
Example
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
There are some other ways to write php code in html document. Those are ,
Short-open tags
Short or short-open tags look like this −
<?...?>
Short tags are, as one might expect, the shortest option You must do one of two things to
enable PHP to recognize.
ASP-style tags
ASP-style tags used by Active Server Pages to delineate code blocks. ASP-style tags look like
this −
<%...%>
To use ASP-style tags, you will need to set the configuration option in your php.ini file.
HTML script tags
HTML script tags look like this −
<script language = "PHP">...</script>
PHP - Variable
Variables are "containers" for storing information.
All variables in PHP are denoted with a leading dollar sign ($).
Variables are no need, to declare before assignment.
PHP does a good job of automatically converting types from one to another when necessary.
Rules for naming a variable is −
Variable names must begin with a letter or underscore character.
A variable name can consist of numbers, letters, underscores only.
Ex : $x
Datatypes:
Integers − are whole numbers, without a decimal point, like 4195.
Doubles − are floating-point numbers, like 3.14159 or 49.1.
Booleans − have only two possible values either true or false.
NULL − is a special type that only has one value: NULL.
Strings − are sequences of characters, like 'PHP supports string operations.'
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can package up both other kinds
of values and functions that are specific to the class.
Resources − are special variables that hold references to resources external to PHP (such as
database connections).
The first five are simple types, and the next two (arrays and objects) are compound - types .
PHP – Operator:
Operator is a symbol which is used to perform an operation. PHP language supports following
type of operators.
Arithmetic Operators
There are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 20 then −
Comparison Operators
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −
== Checks if the value of two operands are equal or not, if yes then (A == B) is
condition becomes true. not true.
> Checks if the value of left operand is greater than the value of (A > B) is not
right operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of right (A < B) is
operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to the (A >= B) is
value of right operand, if yes then condition becomes true. not true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand, if yes then condition becomes true. true.
Logical Operators
There are following logical operators supported by PHP language
Operator Description
&& Called Logical AND operator. If both the operands are non zero then condition
becomes true.
|| Called Logical OR Operator. If any of the two operands are non zero then
condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a
condition is true then Logical NOT operator will make false.
Assignment Operators
There are following assignment operators supported by PHP language −
Operator Description Example
1. if...else statement
2. elseif statement
3. switch statement
If...Else Statement
It follows the below Syntax.
Syntax:
if (condition)
true block;
else
false block;
Example
<html>
<body>
<?php
$x = 5;
$y =10;
if($x>$y)
{
echo "Biggest value is: $x ";
}
else
{
echo "Biggest value is: $y ";
}
?>
</body>
</html>
It will produce the following result −
Biggest value is : 10
ElseIf Statement
It follows the below syntax.
Syntax
if (condition-1)
statements-1;
elseif (condition-2)
statements-2;
else
Statements-3;
Example
<?php
$x = 5;
$y =10;
$z =15;
if($x>$y && $x>$z)
{
echo "Biggest value is: $x ";
}
elseif($y>$z)
{
echo "Biggest value is: $y ";
}
else
{
echo "Biggest value is: $z ";
}
?>
Switch Statement
It is a multiway decision-making statement it follows below syntax.
Syntax
switch (Choice)
{
case value1:
Statements;
break;
case value2:
Statements;
break;
……
……
default:
statemts;
}
Example
<html>
<body>
<?php
$ch=”Add”;
$x=10;
$y=3;
switch ($ch)
{
case "Add":
$z=$x+$y;
echo "Addition is $z";
break;
case "Mul":
$p=$x*$y;
echo "Multiplication is $p";
break;
default:
echo "Enter Correct choice.";
}
?>
</body>
</html>
It will produce the following result −
Addition is 13
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.
1. for
2. while
3. do...while
4. foreach
for loop :
The for statement is used when you know how many times you want to execute a statement or
a block of statements.
Syntax:
Example
<?php
for ($x = 1; $x <= 10; $x++) {
echo “The number is: $x <br>”;
}
?>
while loop :
If the test expression is true then the code block will be executed. After the code has executed
the test expression will again be evaluated and the loop will continue until the test expression is
found to be false.
Syntax:
while (condition)
{
code to be executed;
}
Example
The example below displays the numbers from 1 to 5:
<?php
$x = 1;
while($x <= 5) {
echo “The number is: $x <br>”;
$x++;
}
?>
do…while loop:
The do…while statement will execute a block of code at least once – it then will repeat the loop
as long as a condition is true.
The do- while loop is an exit control loop.
Syntax
do {
code to be executed;
}
while (condition);
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
foreach loop:
The foreach statement is used to loop through arrays. For each pass the value of the current
array element is assigned to $value and the array pointer is moved by one and in the next pass
next element will be processed.
Syntax
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
break statement
Once control reached to Break statement , it will exit from the iteration permanently.
Example
<?php
for ($x = 1; $x <= 10; $x++)
{
if ($x == 4)
{
break;
}
echo "The number is: $x <br>";
}
?>
Output :
The number is : 1
The number is : 2
The number is : 3
continue statement:
Once control reached to continue statement it will skip that iteration and continue with next
iteration.
Example
<?php
for ($x = 1; $x <= 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
Output:
The number is : 1
The number is : 2
The number is : 3
The number is : 5
The number is : 6
The number is : 7
The number is : 8
The number is : 9
The number is : 10
PHP - Functions
PHP functions are similar to other programming languages. A function is a piece of code which
takes one more input in the form of parameter and does some processing and returns a value.
In PHP also we have 2 types of functions. Those are
1. pre-defined functions
2. user defined functions
In PHP we can use functions by these two following steps,
Creating a PHP Function
Calling a PHP Function
Suppose you want to create a PHP function which will simply write a simple message on your
browser when you will call it.
Following example creates a function called Message() and then calls it just after creating it.
while creating a function its name should start with keyword function and all the PHP code
should be put inside { and } braces as shown in the following example below −
<html>
<body>
<?php
/* Defining a PHP Function */
function Message() {
echo "Good morning have a nice day!";
}
</body>
</html>
<html>
<body>
<?php
function add($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
add(10, 20);
?>
</body>
</html>
<html>
<body>
<?php
function add($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$res = add(10, 20);
</body>
</html>
function myTest() {
// using x inside this function will generate an error
echo "Variable x inside function is: $x ";
}
myTest();
Example:
<html>
<body>
<?php
/* First method to create array. */
$x = array( 10, 30, 45);
foreach( $x as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
$y[0] = "one";
$y[1] = "two";
$y[2] = "three";
foreach( $y as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
OUTPUT:
Value is 10
Value is 30
Value is 45
Value is one
Value is two
Value is three
2.Associative Arrays:
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index.
Associative array will have their index as string so that you can establish a strong
association between key and values.
To store student details in an associative array given below.
Example:
<html>
<body>
<?php
/* First method to associate create array. */
$x = array("name"=>"Anil", "marks"=>67 , "group"=>"mpcs");
echo “Name :” .$x["name"]. "<br/>";
?>
</body>
</html>
OUTPUT:
Name: Anil
Result of Anil is Pass
3.Multidimensional Arrays:
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array
are accessed using multiple indexes.
Example:
In this example we create a two-dimensional array to store marks of students in three subjects
<html>
<body>
<?php
$marks = array(
"Anil" => array (
"physics" => 35,
"maths" => 30,
"Computers" => 39
),
);
echo "Marks for Anil in physics : " ;
echo $marks[“Anil”][“physics”] . "<br />";
?>
</body>
</html>
Example
Here is an example which defines a class of Books type −
<?php
class Books
{
var $price;
function setPrice($par)
{
$this->price = $par;
}
function getPrice()
{
echo $this->price ."<br/>";
}
}
?>
The variable $this is a special variable and it refers to the same object i.e.; itself.
Strings:
Strings are sequences of characters; PHP supports string operations.
Following are valid examples of string
$string1 = "Hello World";
$string2 = "welcome to PHP";
<?php
$name = "Anil";
$msg = "Welcome $name";
print($msg);
?>
This will produce the following result −
Welcome Anil
String Concatenation Operator
To concatenate two string variables together, use the dot (.) operator −
<?php
$string1="Hello World";
$string2="1234";
<?php
echo strlen("Hello world!");
?>
This will produce the following result −
12
strpos() function:
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no
match is found, it will return FALSE.
<?php
echo strpos("Hello world!”, “world");
?>
This will produce the following result −
6
As you see the position of the string "world" in our string is position 6.
Strtolower() function :
This function is used to display given string into lower case.
<?php
Echo strtolower(“WORLD”);
?>
This will produce the following result –
world
Strtoupper() function :
This function is used to display given string into uppercase case.
<?php
Echo strtoupper(“world”);
?>
This will produce the following result –
WORLD
Strcmp() function:
The strcmp() function compares two strings.
This function returns:
<?php
echo strcmp("Hello world!","Hello world!");
?>
This will produce the following result –
0
Str_repeat() function :
<?php
echo str_repeat(“hello”,3);
?>
This will produce the following result –
hello hello hello
Example:
<?php
print time();
?>
This will produce the following result −
1480930103
1 seconds 20
Seconds past the minutes (0-59)
2 minutes 29
Minutes past the hour (0 - 59)
3 hours 22
Hours of the day (0 - 23)
4 mday 11
Day of the month (1 - 31)
5 wday 4
Day of the week (0 - 6)
6 mon 7
Month of the year (1 - 12)
7 year 1997
Year (4 digits)
8 yday 19
Day of year ( 0 - 365 )
9 weekday Thursday
Day of the week
10 month January
Month of the year
Example
<?php
$d = getdate();
1 a pm
'am' or 'pm' lowercase
2 A PM
'AM' or 'PM' uppercase
3 d 20
Day of month, a number with leading zeroes
4 h 12
Hour (12-hour format - leading zeroes)
5 i 23
Minutes ( 0 - 59 )
6 m 1
Month of year (number - leading zeroes)
7 s 20
Seconds of hour
8 y 23
Year (two digits)
9 Y 2023
Year (four digits)
Example
Try out following example
<?php
print date("m/d/y h:i:s<br>", time());
echo "<br>";
?>
This will produce following result −
12/05/16 9:29:47
1.Explain how to Combining HTML and PHP code on a single Page with suitable
example.
PHP Form Handling
The example below displays a simple HTML form with two input fields and a submit button:
Example:
<html>
<body>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php".
To display the submitted data you could simply echo all the variables. The "welcome.php" looks
like this:
<html>
<body>
</body>
</html>
Welcome John
Your email address is [email protected]
The same result could also be achieved using the HTTP GET method:
Example:
<html>
<body>
<form action="Hello.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
<html>
<body>
</body>
</html>
The code above is quite simple. However, the most important thing is missing. You need to
validate form data to protect your script from malicious code.
2.Explain how to Creating Forms, Accessing Form Input with User defined Arrays.
PHP - GET & POST Methods
There are two ways the browser client can send information to the web server.
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information to be
sent to the server.
GET can't be used to send binary data, like images or word documents, to the server.
The data sent by GET method can be accessed using QUERY_STRING environment
variable.
The PHP provides $_GET associative array to access all the sent information using
GET method.
Try out following example by putting the source code in test.php script.
<?php
if( $_GET["name"] || $_GET["age"] )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
}
?>
<html>
<body>
</body>
</html>
It will produce the following result −
The POST method transfers information via HTTP headers. The information is encoded as
described in case of GET method and put into a header called QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on
HTTP protocol. By using Secure HTTP you can make sure that your information is
secure.
The PHP provides $_POST associative array to access all the sent information using
POST method.
Try out following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] )
{
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
}
?>
<html>
<body>
</body>
</html>
It will produce the following result −
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We
will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent with both the
GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] )
{
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
}
?>
<html>
<body>
</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.
It will produce the following result −
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
The following example creates a cookie named "user" with the value "John Doe".
We retrieve the value of the cookie "user" using the global variable $_COOKIE.
We also use the isset() function to find out if the cookie is set:
Example:
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name]))
{
echo "Cookie named '" . $cookie_name . "' is not set!";
}
else
{
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example:
<?php
// set the expiration date to one hour ago
setcookie("user", "john", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
4.What is session function. Explain working with session in PHP with example.
PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session.
But on the internet there is one problem: the web server does not know who you are or what
you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages
(e.g. username, favorite color, etc). By default, session variables last until the user closes the
browser.
So; Session variables hold information about one single user, and are available to all pages in
one application.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "LION";
echo "Session variables are set.";
?>
</body>
</html>
Get PHP Session Variable Values
Next, we create another page called "demo_session2.php". From this page, we will access the
session information we set on the first page ("demo_session1.php").
Esxample:
<?php
session_start();
?>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Another way to show all the session variable values for a user session is to run the following
code:
Example :
<?php
session_start();
?>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Modify a PHP Session Variable
Example:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
Destroy a PHP Session
Example:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
1.Explain working with files in PHP.
file inclusion:
PHP allows you to include file so that a page content can be reused many times. It is very
helpful to include files when you want to apply the same HTML or PHP code to multiple pages
of a website.
PHP include is used to include a file on the basis of given path. You may use a relative or
absolute path of the file.
Syntax: include ('filename');
Example:
File: menu.html
<a href="home.html">Home</a>
<a href="php.html">PHP</a>
<a href="java.html">Java</a>
File: include1.php
<?php include("menu.html"); ?>
<h1>This is Main Page</h1>
Output:
Home
PHP
Java
This is Main Page
PHP has several functions for creating, reading, uploading, and editing files.
The fopen() function is used to open files and also used to create a file.
If we use fopen() on a file, and that does not exist, at that time it will create it.
The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened.
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if
it doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist
Example
<?php
$myfile = fopen("Hello.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("Hello.txt"));
fclose($myfile);
?>
Write to File
The first parameter of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Hello \n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Hello
Read File
a) readfile() Function
The readfile() function reads a file and writes it to the output buffer.
Assume we have a text file called "Hello.txt", stored on the server, that looks like this:
The PHP code to read the file and write it to the output buffer is as follows.
Note : the readfile() function returns the number of bytes read on success.
Example
<?php
echo readfile("Hello.txt");
?>
b) fread():
The first parameter of fread() contains the name of the file to read from and the second
parameter specifies the maximum number of bytes to read.
The following PHP code reads the "Hello.txt" file to the end:
fread($myfile,filesize("Hello.txt"));
The example below outputs the first line of the "Hello.txt" file:
Example
<?php
$myfile = fopen("Hello.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgetc() function, the file pointer moves to the next line.
d) fgetc()-Read Single Character
The example below reads the "Hello.txt" file character by character, until end-of-file is reached:
Example
<?php
$myfile = fopen("Hello.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
Note: After a call to the fgetc() function, the file pointer moves to the next character.
Check End-Of-File
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "Hello.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("Hello.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
Close File
The fclose() requires the name of the file (or a variable that holds the filename) we want to
close:
<?php
$myfile = fopen("Hello.txt", "r");
// some code to be executed....
fclose($myfile);
?>
Append Text
You can append data to a file by using the "a" mode. The "a" mode appends text to the end of
the file.
In the example below we open our existing file "newfile.txt", and append some text to it:
Example
<?php
$myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
$txt = "good morning \n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, we will see that Donald Duck and Goofy Goof is appended
to the end of the file:
Hello
Good morning
2.Explain working with directories in PHP.
Working with directories :
The directory functions allow you to retrieve information about directories and their contents.
getcwd():
This function is used to get current working directory.
<?php
chdir("images");
?>
Opendir():
The opendir() function used to open a directory to handle.
Readdir();
The readdir() function is used to read given directory .
Closedir():
Example:
<?php
$dir = getcwd();
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>
3. Explain popen() , Exec() , system() , passthru() commands.
Popen() :
The popen() function in PHP is used to open a pipe to a process using
the command parameter.
Syntax :Popen( command , mode);
<?php
$handle = popen("/bin/ls", "r");
$read = fread($handle, 2096);
print_r("$handle: ".gettype($handle)."\n$read \n");
pclose($handle);
?>
exec() Function
The exec() function is an inbuilt function in PHP which is used to execute an external program
and returns the last line of the output. It also returns NULL if no command run properly.
Syntax:
exec( $command, $return_var )
$command: This parameter is used to hold the command which will be executed.
$return_var: The $return_var parameter is present along with the output argument, then it
returns the status of the executed command will be written to this variable.
Example:
<?php
echo exec('pwd');
?>
System()
system($command, $result_code )
system() is the function in that it executes the given command and outputs the result.
Parameters
command
result_code
If the result_code argument is present, then the return status of the executed command
will be written to this variable.
Return Values
Returns the last line of the command output on success, and false on failure.
Examples
<?php
?>
Passthru()
Syntax :
passthru($command, $result_code)
The passthru() function is similar to the exec() function in that it executes a command.
Parameters
command
result_code
If the result_code argument is present, then the return status of the executed command
will be written to this variable.
Return Values
Returns the last line of the command output on success, and false on failure.
Examples
<?php
?>
4. Explain working with images in PHP with example.
Working with images in PHP:
The imagecreate() is a function in PHP used to create a new image. This function returns the
blank image of given size.
In general imagecreatetruecolor() function is used instead of imagecreate() function
because imagecreatetruecolor() function creates high quality images.
Syntax: imagecreate( $width, $height )
$width: It is mandatory parameter which is used to specify the image width.
$height: It is mandatory parameter which is used to specify the image height.
Return Value: This function returns an image resource identifier on success, FALSE on errors.
Example:
<?php
MySQL vs MySQLi
MySQL and MySQLi are PHP database extensions implemented by using the PHP extension framework.
PHP database extensions are used to write PHP code for accessing the database.
MySQL extension is deprecated and will not be available in future PHP versions. It is recommended to use
the MySQLi extension with PHP 5.5 and above.
MYSQLi MYSQL
MySQLi extension added in PHP 5.5 MySQL extension added in PHP version 2.0
MySQLi supports transactions through API. Transactions are handled by SQL queries only.
MySQLi extension is with enhanced security and MySQL extension lags in security and other
improved debugging. special features, comparatively.
mysql_connect($host_name,$user_name,$pa
mysqli_connect($host_name,$user_name,$passwd,$db
sswd) followed by
name)
mysql_select_db($dbname)
2.Explain How to connect MySQL with PHP and workingwith MySQL data.
PHP Connect to MySQL
Before we can access data in the MySQL database, we need to be able to connect to the server:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Close the Connection
The connection will be closed automatically when the script ends. To close the connection before, use the
following:
mysqli_close($conn);
Example
<?php
$servername = "localhost";
$username = "root";
$password = "root";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE College";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
A database table has its own unique name and consists of columns and rows.
Example
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "college";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $que)) {
echo "Table Student created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
After a database and a table have been created, we can start adding data in them.
The INSERT INTO statement is used to add new records to a MySQL table:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $que)) {
echo "New record created successfully";
} else {
echo "Error: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
The following examples delete the record with id=1 in the "Student" table:
Example
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "College";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
The SELECT statement is used to select data from one or more tables:
Example
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "College";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_close($conn);
?>