WT Notes - PHP PDF
WT Notes - PHP PDF
PHP - Hypertext Preprocessor is an open source, interpreted and object-oriented scripting language i.e.
executed at server side. It is used to develop web applications (an application i.e. executed at server side
and generates dynamic page).
PHP Features
Performance: Script written in PHP executes much faster then those scripts written in other
Open Source Software: PHP source code is free available on the web, you can developed all
the version of PHP according to your requirement without paying any cost.
Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX operating
system. A PHP application developed in one OS can be easily executed in other OS also.
Compatibility: PHP is compatible with almost all local servers used today like Apache, IIS etc.
Embedded: PHP code can be easily embedded within HTML tags and script.
PHP Example
File: hello.php
<!DOCTYPE>
<html>
<body>
<?php
echo "<h2>Hello by PHP</h2>";
?>
</body>
</html>
PHP Echo
PHP echo is a language construct not a function, so you don't need to use parenthesis with it. But if you
want to use more than one parameters, it is required to use parenthesis.
<?php
$msg="Hello JavaTpoint PHP";
echo "Message is: $msg";
?>
PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the argument
list. Unlike echo, it always returns 1.
<?php
print "Hello by PHP print ";
print ("Hello by PHP print()");
$msg="Hello print() in PHP";
print "Message is: $msg";
?>
PHP Variables
A variable in PHP is a name of memory location that holds data. A variable is a temporary storage that is
used to store data temporarily.
$variablename=value;
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
Output:
The $var (single dollar) is a normal variable with the name var that stores any value like string, integer,
float, etc.
The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.
<?php
$x = "abc";
$$x = 200;
echo $x."<br/>";
echo $$x."<br/>";
echo $abc;
?>
Output:
abc
200
200
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the script. PHP
constants can be defined by 2 ways:
PHP constants follow the same PHP variable rules. For example, it can be started with letter or
underscore only.
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
PHP Data Types
PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types
that can be categorized further in 3 types:
1. Scalar Types
2. Compound Types
3. Special Types
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument list and
return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.
Syntax
function functionname(){
//code to be executed
}
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-
length argument list.
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
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.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
<?php
function sayHello($name="Sonoo"){
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
Output:
Cube of 3 is: 27
PHP Variable Length Argument Function
PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments
in function. To do so, you need to use 3 ellipses (dots) before the argument name.
The 3 dot concept is implemented for variable length argument since PHP 5.6.
<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}
Output:
10
Recursive Function
PHP also supports recursive function call like C/C++. In such case, we call current function within
function. It is also known as recursion.
It is recommended to avoid recursive function call over 200 recursion level because it may smash the
stack and may cause the termination of script.
<?php
function display($number) {
if($number<=5){
echo "$number ";
display($number+1);
}
}
display(1);
?>
Output: 12345
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of
similar type in a single variable.
Advantage
Less Code: We don't need to define multiple variables.
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
Indexed Array
PHP indexed array is an array which is represented by an index number by default. All elements of array
are represented by an index number which starts from 0.
PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric
array.
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output: Season are: summer, winter, spring and autumn
<?php
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>
Output:
Associative Array
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 the salaries of employees in an array, a numerically indexed array would not be the best choice.
Instead, we could use the employees names as the keys in our associative array, and the value would be
their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it would not return
any value.
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
Example
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
foreach($salary as $k => $v) {
echo "Key: ".$k." Value: ".$v."<br/>";
}
?>
Output:
Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an
array. PHP multidimensional array can be represented in the form of matrix which is represented by row
* column.
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
Example
<html>
<body>
<?php
$marks = array(
"ram" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
</body>
</html>
1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)
Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify string
in PHP.
For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use
double backslash (\\). All the other instances with backslash such as \r or \n, will be output same as they
specified instead of having any special meaning.
Example
<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quoted string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
Double Quoted
In PHP, we can specify string through enclosing text within double quote also. But escape sequences and
variables will be interpreted using double quote PHP strings.
<?php
$str1="Hello text
multiple line
text within double quoted string";
$str2="Using double \"quote\" with backslash inside double quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an identifier is provided after
this heredoc <<< operator, and immediately a new line is started to write any text. To close the
quotation, the string follows itself and then again that same identifier is provided. That closing identifier
must begin from the new line without any whitespace or tab.
Naming Rules
The identifier should follow the naming rule that it must contain only alphanumeric characters and
underscores, and must start with an underscore or a non-digit character.
Example
<?php
$city = 'Delhi';
$str = <<<DEMO
Hello! My name is Misthi, and I live in $city.
DEMO;
echo $str;
?>
Output:
We cannot use any whitespace or tab before and after the identifier and semicolon, which means
identifier must not be indented. The identifier must begin from the new line.
Newdoc
Newdoc is similar to the heredoc, but in newdoc parsing is not done. It is also identified with three less
than symbols <<< followed by an identifier. But here identifier is enclosed in single-quote, e.g.
<<<'EXP'. Newdoc follows the same rule as heredocs.
The difference between newdoc and heredoc is that - Newdoc is a single-quoted string whereas
heredoc is a double-quoted string.
<?php
$str = <<<'DEMO'
Welcome to bvrit.
Learn with newdoc example.
DEMO;
echo $str;
echo '</br>';
echo <<< 'Demo' // Here we are not storing string content in variable str.
Welcome to bvrit.
Learn with newdoc example.
Demo;
?>
Output:
The form request may be get or post. To retrieve data from get request, we need to use $_GET, for post
request $_POST.
Let's see a simple example to receive data from get request in PHP.
form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>
The data passed through post request is not visible on the URL browser so it is secured. You can send
large amount of data through post request.
Let's see a simple example to receive data from post request in PHP.
form1.html
<form action="login.php" method="post">
<table>
<tr>
<td>Name:</td>
<td> <input type="text" name="name"/></td>
</tr>
<tr>
<td>Password:</td>
<td> <input type="password" name="password"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="login"/></td>
</tr>
</table>
</form>
login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in $password variable
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.";
exit();
}
?>
<html>
<body>
</body>
</html>
1. include
2. require
Advantage
Code Reusability: By the help of include and require construct, we can reuse HTML code or PHP script
include function: The include() function takes all the text in a specified file and copies it into the file
that uses the include function. If there is any problem in loading a file then the include() function
generates a warning but the script will continue execution.
menu.html
<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>
include1.php
Output:
require function:
The require() function takes all the text in a specified file and copies it into the file that uses the include
function. If there is any problem in loading a file then the require() function generates a fatal error and
halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions. It is
recommended to use the require() function instead of include(), because scripts should not continue
executing if files are missing or misnamed.
menu.html
<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>
require1.php
Output:
Cookie is created at server side and saved to client browser. Each time when client sends request to the
server, cookie is embedded with request. Such way, cookie can be received at the server side.
setcookie() function
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it
by $_COOKIE superglobal variable.
Syntax
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
[, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Example
$_COOKIE
Example
Output:
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
Delete Cookie
If you set the expiration date in past, cookie will be deleted.
<?php
setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
?>
PHP Session
PHP session is used to store and pass information from one page to another temporarily (until user close
the website).
PHP session technique is widely used in shopping websites where we need to store and pass cart
information e.g. username, product code, product name, product price etc from one page to another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict between
multiple browsers.
session_start() function
PHP session_start() function is used to start the session. It starts a new or resumes existing session. It
returns existing session if session is created already. If session is not available, it creates and returns new
session.
Syntax
Example
session_start();
$_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session
variable values.
Example: Store information
$_SESSION["user"] = "Sachin";
echo $_SESSION["user"];
Session Example
session1.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "Sachin";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit next page</a>
</body>
</html>
session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
</html>
<?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
} else {
$_SESSION['counter']++;
}
echo ("Page Views: ".$_SESSION['counter']);
?>
Destroying Session
PHP session_destroy() function is used to destroy all session variables completely.
session3.php
<?php
session_start();
session_destroy();
?>
Open File
PHP fopen() function is used to open file or URL and returns resource. The fopen() function accepts
two arguments: $filename and $mode. The $filename represents the file to be opended and $mode
represents the file mode for example read-only, read-write, write-only etc.
Syntax
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource
$context ]] )
Mode Description
r Opens file in read-only mode. It places the file pointer at the beginning of the file.
r+ Opens file in read-write mode. It places the file pointer at the beginning of the
file.
w Opens file in write-only mode. It places the file pointer to the beginning of the file
and truncates the file to zero length. If file is not found, it creates a new file.
w+ Opens file in read-write mode. It places the file pointer to the beginning of the file
and truncates the file to zero length. If file is not found, it creates a new file.
a Opens file in write-only mode. It places the file pointer to the end of the file. If file
is not found, it creates a new file.
a+ Opens file in read-write mode. It places the file pointer to the end of the file. If
file is not found, it creates a new file.
x Creates and opens file in write-only mode. It places the file pointer at the
beginning of the file. If file is found, fopen() function returns FALSE.
c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it
is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the
case with 'x'). The file pointer is positioned on the beginning of the file
Example
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>
Read File
PHP provides various functions to read data from file. There are different functions that allow you to
read all file data, read data line by line and read data character by character.
o fread()
o fgets()
o fgetc()
fread()
The PHP fread() function is used to read data of the file. It requires two arguments: file resource
and file size.
Syntax
string fread (resource $handle , int $length )
Example
<?php
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r");//open file in read mode
Output
fgets()
The PHP fgets() function is used to read single line from the file.
Syntax
string fgets ( resource $handle [, int $length ] )
Example
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>
Output
fgetc()
The PHP fgetc() function is used to read single character from the file. To get all data using fgetc()
function, use !feof() function inside the while loop.
Syntax
string fgetc ( resource $handle )
Example
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
Output
Write File
PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you need to use
w, r+, w+, x, x+, c or c+ mode.
fwrite()
The PHP fwrite() function is used to write content of the string into file.
Syntax
Example
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);
Output: data.txt
Overwriting File
If you run the above code again, it will erase the previous data of the file and writes the new data. Let's
see the code that writes only new data into data.txt file.
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'hello');
fclose($fp);
Output: data.txt
hello
Append to File
You can append data into file by using a or a+ mode in fopen() function. Let's see a simple example that
appends data into data.txt file.
data.txt
Example
<?php
$fp = fopen('data.txt', 'a');//opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);
Output: data.txt
Delete File
In PHP, we can delete any file using unlink() function. The unlink() function accepts one argument only:
file name. It is similar to UNIX C unlink() function.
PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is deleted
successfully otherwise FALSE.
Syntax
Example
<?php
$status=unlink('data.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>
Output
File Upload
PHP allows you to upload single and multiple files through few lines of code only.
PHP file upload features allows you to upload binary and text files both. Moreover, you can have the full
control over the file to be uploaded through PHP authentication and file operation functions.
$_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file
name, file type, file size, temp file name and errors associated with file.
move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the POST request. It
moves the file if it is uploaded through the POST request.
Syntax
uploader.php
<?php
$target_path = "e:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
Download File
PHP enables you to download file easily using built-in readfile() function. The readfile() function reads a
file and writes it to the output buffer.
readfile() function
Syntax
$use_include_path: it is the optional parameter. It is by default false. You can set it to true to
the search the file in the included_path.
<?php
$file_url = 'http://www.javatpoint.com/f.txt';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: utf-8");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>
<?php
$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>
Directory functions
The directory functions allow you to retrieve information about directories and their contents.
Function Description
chdir()
<?php
// Get current directory
echo getcwd() . "<br>";
// Change directory
chdir("images");
Result:
/home/php
/home/php/images
chroot()
The chroot() function changes the root directory of the current process to directory, and changes the
current working directory to "/".
Note: This function requires root privileges, and is only available to GNU and BSD systems, and only
when using the CLI, CGI or Embed SAPI.
<?php
// Change root directory
chroot("/path/to/chroot/");
Result:
closedir()
Example
<?php
$dir = "/images/";
Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
dir()
The dir() function returns an instance of the Directory class. This function is used to read a directory,
which includes the following:
Both handle and path properties have three methods: read(), rewind(), and close()
Syntax
dir(directory, context)
Example:
<?php
$d = dir(getcwd());
Result:
Handle: Resource id #2
Path: /etc/php
filename: .
filename: ..
filename: ajax.gif
filename: books.xml
filename: cdcatalog.xml
filename: cd_catalog.xml
filename: default.asp
filename: demo_array.asp
filename: demo_array.htm
...
...
...
getcwd()
<?php
echo getcwd();
?>
Result:
/home/php
opendir()
<?php
$dir = "/images/";
Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
readdir()
The readdir() function returns the name of the next entry in a directory.
<?php
$dir = "/images/";
Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
rewinddir()
Example
Open a directory, list its files, reset directory handle, list its files once again, then close:
<?php
$dir = "/images/";
?>
Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
filename: cat.gif
filename: dog.gif
filename: horse.gif
scandir()
The scandir() function returns an array of files and directories of the specified directory.
Example
<?php
$dir = "/images/";
print_r($a);
print_r($b);
?>
Result:
Array
(
[0] => .
[1] => ..
[2] => cat.gif
[3] => dog.gif
[4] => horse.gif
[5] => myimages
)
Array
(
[0] => myimages
[1] => horse.gif
[2] => dog.gif
[3] => cat.gif
[4] => ..
[5] => .
)
PHP MySQL
MySQL is an open-source relational database management system (RDBMS). It is the most popular
database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation.
The data in a MySQL database are stored in tables which consists of columns and rows.
MySQL is very fast, reliable, and easy to use database system. It uses standard SQL
1. MySQLi extension.
Both PDO and MySQLi are object-oriented, but MySQLi also offers a procedural API.
If at some point of development phase, the user or the development team wants to change the
database then it is easy to that in PDO than MySQLi as PDO supports 12 different database
systems. He would have to only change the connection string and a few queries. With MySQLi,
he will need to rewrite the entire code including the queries.
MySQL Connect
Since PHP 5.5, mysql_connect() extension is deprecated we use mqsqli_connect() to connect.
PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database. It returns resource if
connection is established or null.
Syntax
PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if connection
is closed or false.
Syntax
bool mysqli_close(resource $resource_link)
Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>
Output:
Connected successfully
In MySQLi procedural approach instead of creating an instance we can use the mysqli_connect() function
available in PHP to establish a connection. This function takes the information as arguments such as host,
username, password, database name etc. This function returns MySQL link identifier on successful
connection or FALSE when failed to establish a connection.
Create Database
If the MySQL connection is established using procedural procedure then we can use the mysqli_query()
function of PHP to execute our query as described in the below syntax.
Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
if(mysqli_query( $conn,$sql)){
echo "Database mydb created successfully.";
}else{
echo "Sorry, database creation failed ".mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Connected successfully
Database mydb created successfully.
Create Table
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydb';
$sql = "create table emp(id INT AUTO_INCREMENT, name VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL, primary key (id))";
if(mysqli_query($conn, $sql)){
echo "Table emp created successfully";
}else{
echo "Could not create table: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Connected successfully
Table emp created successfully
Insert Record
Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydb';
mysqli_close($conn);
?>
Output:
Connected successfully
Record inserted successfully
Update Record
Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydb';
$id = 2;
$name = "Rahul";
$salary = 80000;
$sql = "update emp set name=\"$name\", salary=$salary where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record updated successfully";
}else{
echo "Could not update record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Connected successfully
Record updated successfully
Delete Record
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydb';
$id=2;
$sql = "delete from emp where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record deleted successfully";
}else{
echo "Could not deleted record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Connected successfully
Record deleted successfully
Select Query
There are two other MySQLi functions used in select query.
Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydb';
$conn = mysqli_connect($host, $user, $pass, $dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
Output:
Connected successfully
EMP ID :1
EMP NAME : ratan
EMP SALARY : 9000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------