PHP & Mysql: Sri Harshini Degree College - Ongole B.Sc-Vi Sem
PHP & Mysql: Sri Harshini Degree College - Ongole B.Sc-Vi Sem
Performance: Script written in PHP executes much faster then those scripts written
in other languages such as JSP & ASP.
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 files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as
plain HTML
Why PHP?
• Variables
• Data types
• Operators
• Expressions
• Constants.
PHP variables:
• Variables are “containers” for storing information.
• A PHP variable is a named memory location that holds data.
• A variable is a temporary storage that is used to store data temporarily.
• In PHP, a variable is declared using $ sign followed by variable name.
Rules for PHP variables:
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different
variables)
• The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
$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:
$x = ”Hello world!”;
$y = ’Hello world!’;
Integer
• An integer data type is a non-decimal number.
Rules for integers:
Float
A float (floating point number) is a number with a decimal point.
Ex:- $x=10.35;
Ex:- $x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about conditional
testing in a later chapter of this tutorial.
Array
• An array stores multiple values in one single variable.
• In the following example $cars is an array.
Ex:-
$cars = array(“Volvo”,”BMW”,”Toyota”);
Object
• An object is a data type which stores data and information and it can process that
data.
• In PHP, an object must be explicitly declared.
NULL Value
• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value assigned to it.
• Tip: If a variable is created without a value, it is automatically assigned a value of
NULL.
• Variables can also be emptied by setting the value to NULL:
Ex:-
$x = null;
Resource
• Resource is a special data type is not an actual data type.
• It is the storing of a reference to functions and resources external to PHP.
PHP Operators:
PHP Operator is a symbol. Operators are used to perform operations on variables and
values. PHP divides the operators in the following groups:
Ex:-
“hello”.” world”
Output:-
“hello world”
Constants:-
A constant is an identifier (name) for a simple value. The value cannot be changed
during the script. A valid constant name starts with a letter or underscore (no $ sign
before the constant name).
Note: Unlike variables, constants are automatically global across the entire script.
Syntax:
Parameters:
ex:-
• If –Else
• Switch
• For
• While
• Do-while
If-Else:-
PHP if else statement is used to test condition. There are various ways to use if
statement in PHP.
• if
• if-else
• if-else-if
• nested if
PHP If Statement
Syntax:-
if(condition)
{
//code to be executed
}
Flowchart:-
Example:-
<?php
$num=12;
if($num<100)
{
echo ”$num is less than 100";
}
echo ”Bye”;
?>
Syntax:-
if(condition)
else
Flowchart:-
PHP Switch:-
PHP switch statement is multi way decision making statement.
This statement is used when the program contains many number of conditions like if-
else-if.
Syntax:-
switch(expression)
case value1:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
1. Variable initialization
2. Condition or expression
• While loop
• Do – while loop
• For loop
While Loop:-
While loop is an entry control loop.
Condition is checked and if it is true, then group of statements or body of loop is executed.
It will execute again and again till condition becomes false.
Syntax -
Block of statements;
Increment/decrement operator;
Statement –x;
Flow Chart:-
Example-
<?php
$n=1;
while($n<=10)
{
echo ”$n<br/>”;
$n++;
}
?>
Do – while Loop:-
Do - While is an exit control loop. First body of the loop is executed and then the
condition is checked. If condition is true, then body of the loop is executed otherwise it will
exit from loop.
Syntax -
do
Block of statements;
Increment/decrement operator;
Statement –x;
Flow Chart :-
Example:
<?php
$n=1;
do
{
echo ”$n<br/>”;
$n++;
}
while($n<=10);
?>
For Loop:-
When a user want to execute set of statements repeatedly until the specified
condition is false then we use for loops.
Syntax -
Block of loop;
Statement –x;
The initial expression is at the beginning of for loop. Then, the test expression is checked
by the program. If the test expression is false, for loop is terminated. But, if test expression is
true then, the statements are executed and update expression is updated.
Flow Chart: -
Example:-
<?php
for($n=1;$n<=10;$n++)
{
echo ”$n<br/>”;
}
?>
If $display_prices is set to true in part -I line 2, the table is printed. For the sake
of readability, we split the output into multiple print() statements, and once again escape
any quotation marks.
Put these lines into a text file called testmultiprint.php, and place this file in your
Web server document root. When you access this script through your Web browser, it
should look like bellow Figure
In the PART-II the important thing to note here is that the shift to HTML mode on
line 5 only occurs if the condition of the if statement is fulfilled. This can save us the
bother of escaping quotation marks and wrapping our output in print() statements. It
might, however, affect the readability of our code in the long run, especially as our script
grows larger.
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.
•Besides the built-in PHP functions, we can create our own functions.
Syntax:-
function functionName()
code to be executed;
Example:-
<?php
function sayHello($name)
{
echo ”Hello $name<br/>”;
}
sayHello(“Sonoo”);
sayHello(“Vimal”);
sayHello(“John”);
?>
We can specify a default argument value in function. While calling PHP function
if you don’t specify any argument, it will take the default argument. Let’s see a simple
example of using default argument value in PHP function
<?php
function sayHello($name=”Sonoo”)
{
echo ”Hello $name<br/>”;
}
sayHello(“Rajesh”);
sayHello();//passing no value
sayHello(“John”);
?>
Local variables within functions have a short life. After executing the function
local variables are died.
Let’s assume that we want a function to keep track of the number of times it
has been called so that numbered headings can be created by a script. We could, of
course, use the global statement to do this
<?php
$num_of_calls = 0;
function numberedHeading($txt)
{
global $num_of_calls;
$num_of_calls++;
echo “<h1>”.$num_of_calls.” “.$txt.”</h1>”;
}
numberedHeading(“mobiles”);
echo “<p>We build a fine range of tablets.</p>”;
numberedHeading(“tablets”);
echo “<p>Finest in the world.</p>”;
?>
The scope of a variable is the part of the script where the variable can be
referenced/used.
• local
• global
• static
Global and Local Scope:-
A variable declared inside a function has a LOCAL SCOPE and can only be
accessed INSIDE a function:
Example:-
function myTest() {
// using x inside this function will generate an error
echo ”<p>Variable x inside function is: $x</p>”;
}
myTest();
echo ”<p>Variable x outside function is: $x</p>”;
?>
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
Example:-
<?php
function myTest() {
$x = 5; // local scope
echo ”<p>Variable x inside function is: $x</p>”;
}
myTest();
You can have local variables with the same name in different functions,
because local variables are only recognized by the function in which they are
declared.
To do this, use the global keyword before the variables (inside the function):
Example:-
<?php
$x = 5;
$y = 10;
Example:-
<?php
$x = 5;
$y = 10;
function myTest()
{
$GLOBALS[‘y’] = $GLOBALS[‘x’] + $GLOBALS[‘y’];
}
myTest();
echo ”$y”; // outputs 15
?>
PHP The static Keyword:-
To do this, use the static keyword when you first declare the variable:
Example:-
<?php
function myTest() {
static $x = 0;
echo ”$x “;
$x++;
}
myTest();
myTest();
myTest();
?>
b) 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.
Program:
<?php
/* First method to associate create array. */
$salaries = array(“mani” => 2000, “raju” => 1000, “krishna” => 500);
c) Multidimensional Arrays
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.
Example
$emp = array
(
array(1,”sonoo”,400000),
array(2,”john”,500000),
array(3,”rahul”,300000)
);
Page No:31 PHP&MYSQL
Sri Harshini Degree College. B.com:Sem-VI
Program:-
<?php
$emp = array
(
array(1,”sonoo”,400000),
array(2,”john”,500000),
array(3,”rahul”,300000)
);
<?php
$names=array(“krishna”,”raju”,”ravi”,”murali”);
echo ”Names are: $names[0], $names[1], $names[2] and $names[3]”;
?>
<?php
$salary=array(“Sonoo”=>”550000",”Vimal”=>”250000",”Ratan”=>”200000");
print_r(array_change_key_case($salary,CASE_UPPER));
?>
<?php
$names=array(“krishna”,”khan”,”kasi”,”karuna”);
sort($names);
foreach( $names as $s )
{
echo ”$s<br />”;
}
?>
<?php
$names=array(“krishna”,”raju”,”ravi”,”murali”);
$reversenames=array_reverse($names);
foreach( $reversenames as $s )
{
echo ”$s<br />”;
}
?>
<?php
$names=array(“krishna”,”raju”,”ravi”,”murali”);
$key=array_search(“ravi”,$names);
echo $key;
?>
<?php
$a=array(5,15,25);
echo array_sum($a);
?>
Q3) Explain about how to create an Object in PHP:-
Object in Java
e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical.
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance (result) of a class.
Object Definitions:
In PHP declare a class using the class keyword, followed by the name of the class and
a set of curly braces ({}).
<?php
class MyClass
?>
After creating the class, a new class can be instantiated and stored in a variable using the
new keyword:
Syntax:-
In PHP, to see the contents of the class, use var_dump(). The var_dump() function is
used to display structured information (type and value) about one or more variables.
Object:
An individual instance of the data structure defined by a class. You define a class
once and then make many objects that belong to it. Objects are also known as instance.
<?php
class phpClass
{
var $var1;
var $var2 = “constant string”;
function myfunc ($arg1, $arg2)
{
[..]
}
[..]
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>
string is a sequence of characters i.e. used to store and manipulate text. There are 4
ways to specify string in PHP.
Single quoted
Double quoted
It is simple and easy way to specify string in php. We can create a string in PHP by
enclosing text in a single quote.
<?php
$str=’Hello php I am single quote String’;
echo $str;
?>
Output:-
Hello php I am single quote String
In PHP, we can also specify string through enclosing text within double quote
<?php
$str=”Hello php I am double quote String”;
echo $str;
?>
Output:
String functions:-
PHP have lots of predefined function which is used to perform operation with
string some functions are strlen(), strrev(), strpos() etc.
PHP strlen() function
strlen() function returns the length of a string. In below example strlen() function is
used to return length of “Hello world!”
strlen() example in php
<?php
?>
Output
12
?>
Output
2
?>
Output
!dlrow olleH
?>
Output
6
?>
Output
Hello Faiz!
?>
Output
hello friends i am hitesh
?>
Output
HELLO FRIENDS I AM HITESH
■ The computer stores dates and times in a format called UNIX Timestamp, which
measures time as a number of seconds since the beginning of the Unix time format.
Ex:-
<?php
$today = date(“d/m/Y”);
echo $today;
?>
·d - Represent day of the month; two digits with leading zeros (01 or 31)
·D - Represent day of the week in text as an abbreviation (Mon to Sun)
·m - Represent month in numbers with leading zeros (01 or 12)
·M - Represent month in text, abbreviated (Jan to Dec)
·y - Represent year in two digits (08 or 14)
·Y - Represent year in four digits (2008 or 2014)
Ex:-
<?php
echo date(“d/m/Y”) . “<br>”;
echo date(“d-m-Y”) . “<br>”;
echo date(“d.m.Y”);
?>
The PHP time() Function:-
The time() function is used to get the current time as a Unix timestamp (the number
of seconds since the beginning of the Unix epoch: January 1 1970 00:00:00 GMT).
Ex:-
<?php
// Executed at March 05, 2014 07:19:18
$timestamp = time();
echo($timestamp);
?>
The above example produce the following output.
1394003958
We can convert this timestamp to a human readable date through passing it to the
previously introduce date() function.
Example:-
<?php
$timestamp = 1394003958;
echo(date(“F d, Y h:i:s”, $timestamp));
?>
The following example displays the timestamp corresponding to 3:20:12 pm on May 10,
2014:
Example:-
<?php
// Create the timestamp for a particular date
echo mktime(15, 20, 12, 5, 10, 2014);
?>
End of unit-II
Post request is widely used to submit form that have large amount of data such as
file upload, image upload, login form, registration form etc.
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.
File: form1.html
<html>
<body>
<form action=”login.php” method=”post”>
Name: <input type=”text” name=”name”><br>
E-mail: <input type=”text” name=”email”><br>
<input type=”submit”>
</form>
</body>
</html>
File: login.php
<?php
$name=$_POST[“name”];//receiving name field value in $name variable
$email=$_POST[“email”];//receiving password field value in $password variable
echo “Welcome: $name<br/> your E-mail Id is: $email”;
?>
PHP mail() function is used to send email in PHP. You can send text message, html message
and attachment with message using PHP mail() function.
mail(string$to,string$subject,string$message[,string$additional_headers[,string$additional_parameters]]);
$to: specifies receiver or receivers of the mail. The receiver must be specified one of
the following forms.
[email protected]
[email protected], [email protected]
User <[email protected]>
User <[email protected]>, Another User <[email protected]>
$subject: represents subject of the mail.
$message: represents message of the mail to be sent.
Note: Each line of the message should be separated with a CRLF ( \r\n ) and lines should not
be larger than 70 characters.
$additional_headers (optional):
specifies the additional headers such as From, CC, BCC etc. Extra additional headers
should also be separated with CRLF ( \r\n ).
if(move_uploaded_file($_FILES[‘fileToUpload’][‘tmp_name’], $target_path)) {
echo ”File uploaded successfully!”;
} else{
echo ”Sorry, file not uploaded, please try again!”;
}
?>
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.
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.
Syntax:
PHP $_COOKIE:-
File: cookie1.php
<?php
setcookie(“user”, ”Murali”);
?>
<html>
<body>
<?php
if(!isset($_COOKIE[“user”])) {
echo ”Sorry, cookie is not found!”;
} else {
echo ”<br/>Cookie Value: ” . $_COOKIE[“user”];
}
?>
</body>
</html>
Output:
Sorry, cookie is not found!
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
File: cookie1.php
<?php
setcookie (“CookieName”, ””, time() - 3600);// set the expiration date to one hour ago
?>
· 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.
Syntax:
Example:
session_start();
PHP $_SESSION:-
PHP $_SESSION is an associative array that contains all session variables. It is used to
set and get session variable values.
$_SESSION[“user”] = ”Sachin”;
File: 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>
File: session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo ”User is: ”.$_SESSION[“user”];
?>
</body>
</html>
When building a complex page, at some point you will be faced with the need to combine
PHP and HTML to achieve your needed results. At first point, this can seem complicated, since
PHP and HTML are two separate languages, but this is not the case. PHP is designed to interact
with HTML and PHP scripts can be included in an HTML page without a problem.
In an HTML page, PHP code is enclosed within special PHP tags. When a visitor opens
the page, the server processes the PHP code and then sends the output (not the PHP code
itself) to the visitor’s browser. Actually it is quite simple to integrate HTML and PHP. A PHP
If you look at the example below you can see what a full PHP script might look like:
EX:-
<html>
<head></head>
<body class=”page_bg”>
Hello, today is
<?php
echo date(‘M, d, Y, H, i, sa’);
?>
</body>
</html>
Example:-
<html>
<head></head>
<body>
<ul>
<?php
for($i=1;$i<=5;$i++)
{
?>
<li>Menu Item
<?php echo $i; ?>
</li>
<?php
}
?>
</ul>
</body>
</html>
End of unit-III
· include
· require
Advantage
Code Reusability: By the help of include and require construct, we can reuse HTML
code or PHP script in many PHP scripts.
PHP include example
PHP include is used to include file on the basis of given path. Let’s see a simple PHP
include example.
File: footer.php
<?php
Echo “copy right by N Murali Krishna Mtech “;
?>
File: include1.html
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include ’footer.php’;?>
</body>
</html>
require():-
The include() and require() statement allow you to include the code contained in a
PHP file within another PHP file. Including a file produces the same result as copying the script
from the file specified and pasted into the location where it is called.
You can save a lot of time and work through including files — Just store a block of code
in a separate file and include it wherever you want by include() and require() statement instead
of typing the entire block of code multiple times.
files on your web server using the PHP file system functions.
· fopen()
· fread()
· fwrite()
· rename()
· fclose()
The fread() function can be used to read a specified number of characters from a file.
?>
Example
<?php
unlink(‘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);
echo ”File appended successfully”;
?>
<?php
// The directory path
$dir = “testdir”;
<?php
// Source file path
$file = “example.txt”;
} else{
echo “ERROR: File does not exist.”;
?>
To make this example work, the target directory which is backup and the
source file i.e. “example.txt” has to exist already;
otherwise PHP will generate an error.
<?php
echo ’<pre>’;
Exec():-
exec — Execute an external program.
Description:-
string exec ( string $command [, array &$output [, int &$return_var ]] )
exec() executes the given command.
<?php
// outputs the username that owns the running php/httpd process
// (on a system with the ”whoami” executable in the path)
echo exec(‘whoami’);
?>
Passthru():-
passthru — Execute an external program and display raw output.
Description
void passthru ( string $command [, int &$return_var ] )
function create_image()
{
$im = @imagecreate(200, 200) or die(“Cannot Initialize new GD image stream”);
$background_color = imagecolorallocate($im, 255, 255, 0); // yellow
imagepng($im,”image.png”);
imagedestroy($im);
}
?>
Draw line:-
<?php
create_image();
print ”<img src=image.png?”.date(“U”).”>”;
function create_image(){
$im = @imagecreate(200, 200) or die(“Cannot Initialize new GD image stream”);
$background_color = imagecolorallocate($im, 255, 255, 0); // yellow
imagepng($im,”image.png”);
imagedestroy($im);
}
?>
Draw rectangle:-
<?php
create_image();
print ”<img src=image.png?”.date(“U”).”>”;
function create_image(){
$im = @imagecreate(200, 200) or die(“Cannot Initialize new GD image
stream”);
$background_color = imagecolorallocate($im, 255, 255, 0); // yellow
imagepng($im,”image.png”);
imagedestroy($im);
}
?>
Draw ellipse:-
<?php
create_image();
print ”<img src=image.png?”.date(“U”).”>”;
function create_image(){
$im = @imagecreate(200, 200) or die(“Cannot Initialize new GD
image stream”);
$background_color = imagecolorallocate($im, 255, 255, 0); //
yellow
imagepng($im,”image.png”);
imagedestroy($im);
}
?>
function create_image(){
$im = @imagecreate(200, 200)or die(“Cannot Initialize new GD image
stream”);
$background_color = imagecolorallocate($im, 255, 255, 0); // yellow
$red = imagecolorallocate($im, 255, 0, 0); // red
imagepng($im,”image.png”);
imagedestroy($im);
}
?>
output:-
End of unit-IV
There are too many differences between these PHP database extensions. These
differences are based on some factors like performance, library functions, features, benefits,
and others.
·LENGTH & CHAR_LENGTH – get the length of strings in bytes and in characters.
MySQLi-Functions:-
1)mysqli_connect()
2)PDO:: construct()
PHP mysqli_connect()
Syntax
PHP mysqli_close()
Syntax
Example
<?php
$host = ’localhost:3306';
$user = ’’;
$pass = ’’;
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
}
echo ’Connected successfully’;
mysqli_close($conn);
?>
The hostname parameter in the above syntax specify the host name (e.g. localhost),
or IP address of the MySQL server, whereas the username and password parameters specifies
the credentials to access MySQL server, and the database parameter, if provided will specify
the default MySQL database to be used when performing queries.
// Check connection
if($link === false){
die(“ERROR: Could not connect. “ . mysqli_connect_error());
}
Before saving or accessing the data, we need to create a database first. The CREATE
DATABASE statement is used to create a new database in MySQL.
Let’s make a SQL query using the CREATE DATABASE statement, after that we will
execute this SQL query through passing it to the PHP mysqli_query() function to finally
create our database. The following example creates a database named demo.
Example:-
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user ‘root’ with no password) */
$link = mysqli_connect(“localhost”, “root”, “”);
// Check connection
if($link === false){
die(“ERROR: Could not connect. “ . mysqli_connect_error());
}
// Close connection
mysqli_close($link);
?>
Example:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Close connection
mysqli_close($link);
?>
Let’s make a SQL query using the CREATE TABLE statement, after that we will execute
this SQL query through passing it to the PHP mysqli_query() function to finally create our table.
Example:-
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user ‘root’ with no password) */
$link = mysqli_connect(“localhost”, “root”, “”, “demo”);
// Check connection
if($link === false){
die(“ERROR: Could not connect. “ . mysqli_connect_error());
}
Q6) Explain how to view records from the table using PHP.
View/Selecting Data From Database Tables
The SQL SELECT statement is used to select the records from database tables. Its
basic syntax is as follows:
Let’s make a SQL query using the SELECT statement, after that we will execute this
SQL query through passing it to the PHP mysqli_query() function to retrieve the table data.
+——+——————+—————+———————————+
+——+——————+—————+———————————+
+——+——————+—————+———————————+
The PHP code in the following example selects all the data stored in the persons table (using
the asterisk character (*) in place of column name selects all the data in the table).
Example:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Close connection
mysqli_close($link);
?>
Q7)How to delete table record using PHP.(Delete Mechanism)
Deleting Database Table Data
We can delete records from a table using the SQL DELETE statement. It is typically
used in conjugation with the WHERE clause to delete only those records that matches
specific criteria or condition.
Let’s make a SQL query using the DELETE statement and WHERE clause, after that we
will execute this query through passing it to the PHP mysqli_query() function to delete the
tables records.
+——+——————+—————+———————————+
+——+——————+—————+———————————+
+——+——————+—————+———————————+
The PHP code in the following example will delete the records of those persons from
the persons table whose first_name is equal to John.
Example Program:-
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
For example, imagine a book store. This could be represented by a table called
books and has fields for id, title, publisher and author. But instead of placing a name
in the author column, you could instead put the ID value of a author in a separatetable
called authors that has information on authors such as id, name, and email.
Therefore, if you need to update an author’s email, you only need to do so in single
(authors (parent)) table, instead in multiple rows of books table.
******THE END******