PHP_MySQL_notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Opening Database Connection:

PHP mysql_connect() Function


PHP provides mysql_connect() function to open a database connection. This function takes five
parameters and returns a MySQL link identifier on success, or FALSE on failure.

Syntax
connection mysql_connect($server,$user,$passwd,$new_link,$client_flag);

Sr.No Parameter & Description

1
server
Optional − The host name running the database server. It can also include a port number,
e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost. If
not specified then default value is localhost:3306.

2
user
Optional − The username accessing the database. If not specified then default is the
name of the user that owns the server process.

3
passwd
Optional − The password of the user accessing the database. If not specified then default
is an empty password.

4
new_link
Optional − If a second call is made to mysql_connect() with the same arguments, no new
connection will be established; instead, the identifier of the already opened link
(connection) will be returned. The new_link parameter modifies this behaviour and
makes mysql_connect() always open a new link, even if mysql_connect() was called
before with the same parameters.

5
client_flags
Optional − A combination of the following constants −
• MYSQL_CLIENT_SSL − Use SSL encryption
• MYSQL_CLIENT_COMPRESS − Use compression protocol
• MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names
• MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of
inactivity before closing the connection
Return Values:
Returns a MySQL link identifier on success or false on failure.

PHP mysqli_connect() Function


The mysqli_connect() function establishes a connection with MySQL server and returns the
connection as an object.

Syntax
mysqli_connect($host, $username, $passwd, $dbname, $port, $socket)

Parameters
Sr.No Parameter & Description

1
host(Optional)
This represents a host name or an IP address. If you pass Null or localhost as a value to
this parameter, the local host is considered as host.

2
username(Optional)
This represents a user name accessing the database.

3
passwd(Optional)
This represents the password of the user accessing the database.

4
dbname(Optional)
This represents the default database on which the queries should be performed.

5
port(Optional)
This represents the port number at which you want to establish a connection to MySQL
Server.

6
socket(Optional)
This represents the socket that is to be used.
Return Values
If a connection gets established successfully to the MySQL server, the PHP
mysqli_connect() function returns the connection object. In case of an unsuccessful
connection this function returns the boolean value false.

PHP Version
This function was first introduced in PHP Version 5 and works in all the later versions.

Example
Following example demonstrates the usage of the mysqli_connect() function (in
procedural style) −

<?php
$host = "localhost";
$username = "root";
$passwd = "password";
$dbname = "mydb";

//Creating a connection
$con = mysqli_connect($host, $username, $passwd, $dbname);

if($con){
print("Connection Established Successfully");
}else{
print("Connection Failed ");
}
?>

Closing Database Connection:


PHP provides its simplest function mysql_close() to close a database connection.
This function takes connection resource returned by mysql_connect function. It
returns TRUE on success or FALSE on failure.

Syntax
bool mysql_close(resource $link_identifier);
If a resource is not specified then last opened database is closed.

Example
Try out following example to open and close a database connection −

<?php

$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';


mysql_close($conn);
?>

PHP mysqli_query() Function


Definition and Usage
The mysqli_query() function accepts a string value representing a query as one of
the parameters and, executes/performs the given query on the database.

Syntax
mysqli_query($con, $query, $mode)

Parameters
Sr.No Parameter & Description

1
con(Mandatory)
This is an object representing a connection to MySQL Server.

2
query(Mandatory)
This is a string value representing the query to be executed.

3
mode(Optional)
This is an integer value representing the result mode. You can
pass MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT as values to this
parameter.

Return Values
For SELECT, SHOW, DESCRIBE and EXPLAIN queries, this function returns
a mysqli_result object holding the result of the query in case of success and, or false
if failed.
For other queries this function returns a boolean value which is, true if the
operation/query is successful and, false if not.
PHP Version
This function was first introduced in PHP Version 5 and works works in all the later
versions.

Example
Following example demonstrates the usage of the mysqli_query() function (in procedural
style) −

<?php
$con = mysqli_connect("localhost", "root", "password", "mydb");

mysqli_query($con, "CREATE TABLE IF NOT EXISTS my_team(ID INT, First_Name


VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country
VARCHAR(255))");
print("Table Created ..."."\n");

//Inserting a records into the my_team table


mysqli_query($con, "insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi', 'India')");
mysqli_query($con, "insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown',
'SouthAfrica')");
mysqli_query($con, "insert into my_team values(3, 'Kumara', 'Sangakkara', 'Matale',
'Srilanka')");
mysqli_query($con, "insert into my_team values(4, 'Virat', 'Kohli', 'Delhi', 'India')");

print("Records Inserted ..."."\n");

//Closing the connection


mysqli_close($con);
?>

This will produce following result −


Table Created ...
Records Inserted ...
If you observe the contents of the table in the database you can see the inserted
records as shown below −
mysql> select * from my_team;
+------+---------------+---------------+--------------------+----------------+
| ID | First_Name | Last_Name | Place_Of_Birth | Country |
+------+---------------+----------------+-------------------+----------------+
| 1 | Shikhar | Dhawan | Delhi | India |
| 2 | Jonathan | Trott | CapeTown | SouthAfrica |
| 3 | Kumara | Sangakkara | Matale | Srilanka |
| 4 | Virat | Kohli | Delhi | India |
+-------+---------------+----------------+------------------+----------------+
4 rows in set (0.00 sec)
Example
In object-oriented style the syntax of this function is $con->query(); Following is the
example of this function in object oriented style $minus;

<?php
$con = new mysqli("localhost", "root", "password", "mydb");

//Inserting a records into the players table


$con->query("CREATE TABLE IF NOT EXISTS players(First_Name VARCHAR(255),
Last_Name VARCHAR(255), Country VARCHAR(255))");
$con->query("insert into players values('Shikhar', 'Dhawan', 'India')");
$con->query("insert into players values('Jonathan', 'Trott', 'SouthAfrica')");

print("Data Created......");
//Closing the connection
$res = $con -> close();
?>

This will produce following result −


Data Created......
If you observe the contents of the table in the database you can see the inserted
records as shown below −

mysql> select * from players;


+---------------+--------------+-----------------+
| First_Name | Last_Name | Country |
+---------------+-------------- +----------------+
| Shikhar | Dhawan | India |
| Jonathan | Trott | SouthAfrica |
+---------------+---------------+----------------+
2 rows in set (0.00 sec)

Example
Following example prints the results of INSERT and SELECT queries −

<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");

mysqli_query($con, "CREATE TABLE IF NOT EXISTS my_team(ID INT, First_Name


VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country
VARCHAR(255))");
print("Table Created ..."."\n");

//Inserting a records into the my_team table


$res = mysqli_query($con, "insert into my_team values(1, 'Shikhar', 'Dhawan', 'Delhi',
'India')");
print("Result of Insert Query: ".$res."\n");
$res = mysqli_query($con, "insert into my_team values(2, 'Jonathan', 'Trott', 'CapeTown',
'SouthAfrica')");
print("Result of Insert Query: ".$res);
$res = mysqli_query($con, "SELECT * FROM my_team");
print("Result of the SELECT query: ");
print_r($res);

//Closing the connection


mysqli_close($con);
?>

This will produce following result −


Table Created ...
Result of Insert Query: 1
Result of Insert Query: 1Result of the SELECT query: mysqli_result Object
(
[current_field] => 0
[field_count] => 5
[lengths] =>
[num_rows] => 2
[type] => 0
)

Example
Assume that we have created a table ‘Players’ in the database and populated it as
shown below −

CREATE TABLE Players (Name VARCHAR(255), Age INT, Score INT);


insert into Players values('Dhavan', 33, 90),('Rohit', 28, 26),('Kohli', 25, 50);

Following example retrieves the resultset from a mysqli_query() function −

<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");

//Executing the multi query


$query = "SELECT * FROM players";

//Retrieving the records


$res = mysqli_query($con, $query, MYSQLI_USE_RESULT);
if ($res) {
while ($row = mysqli_fetch_row($res)) {
print("Name: ".$row[0]."\n");
print("Age: ".$row[1]."\n");
}
}

//Closing the connection


mysqli_close($con);
?>
This will produce following result −
Name: Dhavan
Age: 33
Name: Rohit
Age: 28
Name: Kohli
Age: 25

PHP mysql_query() Function


Syntax
mysqli_query($query, $con)

Parameters
Sr.No Parameter & Description

1
query(Mandatory)
This is a string value representing the query to be executed.

2
con(Mandatory)
This is an object representing a connection to MySQL Server. If the
connection object is not specified, the last connection opened
by mysql_connect() is assumed. If no such link is found, it will try to create
one as if mysql_connect() had been called with no arguments. If no
connection is found or established, an E_WARNING level error is
generated.

Return Values:

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning


resultset, mysql_query() returns a resource on success, or false on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP,


etc, mysql_query() returns true on success or false on error.

Note:
The returned result resource should be passed to mysql_fetch_array(), and other functions
for dealing with result tables, to access the returned data.
Getting Data From MySQL Database
We have several options to fetch data from MySQL database.
The most frequently used option is to use function mysql_fetch_array(). This
function accepts a result object as a parameter and, retrieves the contents of current
row in the given result object, and returns them as an associative or numeric array or
both.

Syntax
mysql_fetch_array(resource $result, int $result_type)

Parameters:
result

The result resource that is being evaluated. This result comes from a call
to mysql_query().
result_type

The type of array that is to be fetched. It's a constant and can take the following
values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH.

Return Values
Returns an array of strings that corresponds to the current row and moves the
internal data pointer ahead, or false if there are no more rows. The type of returned
array depends on how result_type is defined. By using MYSQL_BOTH (default),
you'll get an array with both associative (names of the fields) and numeric indices.
Using MYSQL_ASSOC, you only get associative indices
(as mysql_fetch_assoc() works), using MYSQL_NUM, you only get numeric indices
(as mysql_fetch_row() works).

Following example demonstrates the usage of the mysqli_fetch_array() function (in


procedural style) −

Example 1:
Retrieval of row as an associative array using mysqli_fetch_array():
<?php
$con = mysqli_connect("localhost", "root", "password", "mydb");

mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255),


Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))");
print("Table Created.....\n");
mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi',
'India')");
mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown',
'SouthAfrica')");
mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale',
'Srilanka')");
print("Record Inserted.....\n");

//Retrieving the contents of the table


$res = mysqli_query($con, "SELECT * FROM myplayers");

//Fetching all the rows as arrays


while($row = mysqli_fetch_array($res, MYSQL_ASSOC)){
print("ID: ".$row["ID"]."\n");
print("First_Name: ".$row["First_Name"]."\n");
print("Last_Name: ".$row["Last_Name"]."\n");
print("Place_Of_Birth: ".$row["Place_Of_Birth"]."\n");
print("Country: ".$row["Country"]."\n");
}
//Closing the statement
mysqli_free_result($res);

//Closing the connection


mysqli_close($con);
?>

Output:

Table Created.....
Record Inserted.....
ID: 1
First_Name: Sikhar
Last_Name: Dhawan
Place_Of_Birth: Delhi
Country: India
ID: 2
First_Name: Jonathan
Last_Name: Trott
Place_Of_Birth: CapeTown
Country: SouthAfrica
ID: 3
First_Name: Kumara
Last_Name: Sangakkara
Place_Of_Birth: Matale
Country: Srilanka

Example 2:
Retrieval of row as an associative array using mysqli_fetch_assoc():
<?php
$con = mysqli_connect("localhost", "root", "password", "mydb");

mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255),


Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))");
print("Table Created.....\n");
mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi',
'India')");
mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown',
'SouthAfrica')");
mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale',
'Srilanka')");
print("Record Inserted.....\n");

//Retrieving the contents of the table


$qry="SELECT * FROM myplayers";
$res = mysqli_query($con, $qry);

//Fetching all the rows as arrays


while($row = mysqli_fetch_assoc($res)){
print("ID: ".$row["ID"]."\n");
print("First_Name: ".$row["First_Name"]."\n");
print("Last_Name: ".$row["Last_Name"]."\n");
print("Place_Of_Birth: ".$row["Place_Of_Birth"]."\n");
print("Country: ".$row["Country"]."\n");
}
//Closing the statement
mysqli_free_result($res);

//Closing the connection


mysqli_close($con);
?>

Output:
Table Created.....
Record Inserted.....
ID: 1
First_Name: Sikhar
Last_Name: Dhawan
Place_Of_Birth: Delhi
Country: India
ID: 2
First_Name: Jonathan
Last_Name: Trott
Place_Of_Birth: CapeTown
Country: SouthAfrica
ID: 3
First_Name: Kumara
Last_Name: Sangakkara
Place_Of_Birth: Matale
Country: Srilanka

Example 3:
Retrieval of row as a numeric array using mysqli_fetch_array():
<?php
$con = mysqli_connect("localhost", "root", "password", "mydb");

mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255),


Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))");
print("Table Created.....\n");
mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi',
'India')");
mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown',
'SouthAfrica')");
mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale',
'Srilanka')");
print("Record Inserted.....\n");

//Retrieving the contents of the table


$qry="SELECT * FROM myplayers";
$res = mysqli_query($con, $qry);

//Fetching all the rows as arrays


while($row = mysqli_fetch_array($res, MYSQLI_NUM)){
print("ID: ".$row[0]."\n");
print("First_Name: ".$row[1]."\n");
print("Last_Name: ".$row[2]."\n");
print("Place_Of_Birth: ".$row[3]."\n");
print("Country: ".$row[4]."\n");
}
//Closing the statement
mysqli_free_result($res);

//Closing the connection


mysqli_close($con);
?>

Output:
Table Created.....
Record Inserted.....
ID: 1
First_Name: Sikhar
Last_Name: Dhawan
Place_Of_Birth: Delhi
Country: India
ID: 2
First_Name: Jonathan
Last_Name: Trott
Place_Of_Birth: CapeTown
Country: SouthAfrica
ID: 3
First_Name: Kumara
Last_Name: Sangakkara
Place_Of_Birth: Matale
Country: Srilanka

Retrieval of row as a numeric array using mysqli_fetch_row():


<?php
$con = mysqli_connect("localhost", "root", "password", "mydb");

mysqli_query($con, "CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255),


Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))");
print("Table Created.....\n");
mysqli_query($con, "INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi',
'India')");
mysqli_query($con, "INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown',
'SouthAfrica')");
mysqli_query($con, "INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale',
'Srilanka')");
print("Record Inserted.....\n");

//Retrieving the contents of the table


$res = mysqli_query($con, "SELECT * FROM myplayers");

while ($row = mysqli_fetch_row($res)) {


print("ID: ".$row[0]."\n");
print("First_Name: ".$row[1]."\n");
print("Last_Name: ".$row[2]."\n");
print("Place_Of_Birth: ".$row[3]."\n");
print("Country: ".$row[4]."\n");
}

//Closing the statement


mysqli_free_result($res);

//Closing the connection


mysqli_close($con);
?>

This will produce following result −


Table Created.....
Record Inserted.....
ID: 1
First_Name: Sikhar
Last_Name: Dhawan
Place_Of_Birth: Delhi
Country: India
ID: 2
First_Name: Jonathan
Last_Name: Trott
Place_Of_Birth: CapeTown
Country: SouthAfrica
ID: 3
First_Name: Kumara
Last_Name: Sangakkara
Place_Of_Birth: Matale
Country: Srilanka

PHP echo and print


The echo is used to display the output of parameters that are passed to it. It
displays the outputs of one or more arguments separated by commas. The
print accepts one argument at a time and prints the output of it.
Note: Both are language constructs in PHP programs that are more or less
the same as both are used to output data on the browser screen.
The print statement is an alternative to echo.

PHP echo statement


It is a language construct and never behaves like a function, hence no
parenthesis is required. But the developer can use parenthesis if they want.
The end of the echo statement is identified by the semi-colon (‘;’). It outputs
one or more strings. We can use ‘echo‘ to output strings, numbers, variables,
values, and results of expressions. Below is some usage of echo statements
in PHP:
Displaying Strings: We can simply use the keyword echo followed by the
string to be displayed within quotes. The below example shows how to
display strings with PHP.

<?php
echo "Hello,This is a display string example!";
?>

Output:
Hello,This is a display string example!

Displaying Strings as multiple arguments: We can pass multiple string


arguments to the echo statement instead of a single string argument,
separating them by comma (‘,’) operator. For example, if we have two strings
i.e “Hello” and “World” then we can pass them as (“Hello”, “World”).
<?php
echo "Multiple ","argument ","string!";
?>

Output:
Multiple argument string!

Displaying Variables: Displaying variables with echo statements is also as


easy as displaying normal strings. The below example shows different ways
to display variables with the help of a PHP echo statement.
<?php
// Defining the variables
$text = "Hello, World!";
$num1 = 10;
$num2 = 20;
// Echoing the variables
echo $text."\n";
echo $num1."+".$num2."=";
echo $num1 + $num2;
?>

Output:
Hello, World!
10+20=30

Note:
The (.) operator in the above code can be used to concatenate two strings in
PHP and the “\n” is used for a new line and is also known as line-break.

PHP print statement


The PHP print statement is similar to the echo statement and can be used
alternative to echo many times. It is also a language construct, so we may not
use parenthesis i.e print and print() are both valid.

The main difference between the print and echo statement is that echo does
not behave like a function whereas print behaves like a function.
The print statement can have only one argument at a time and thus can print
a single string. Also, the print statement always returns a value of 1. Like
an echo, the print statement can also be used to print strings and variables.
Below are some examples of using print statements in PHP:

Displaying String of Text: We can display strings with the print statement
in the same way we did with echo statements. The only difference is we
cannot display multiple strings separated by comma(,) with a single print
statement. The below example shows how to display strings with the help
of a PHP print statement.

<?php
print "Hello, world!";
?>

Output:
Hello, world!
Displaying Variables: Displaying variables with print statements is also the
same as that of echo statements. The example below shows how to display
variables with the help of a PHP print statement.
<?php

// Defining the variables


$text = "Hello, World!";
$num1 = 10;
$num2 = 20;

// Echoing the variables


print $text."\n";
print $num1."+".$num2."=";
print $num1 + $num2;
?>

Output:
Hello, World!
10+20=30

Difference between echo and print statements in PHP:

Sl. No. echo statement print statement

echo accepts a list of arguments (multiple print accepts only one


1. arguments can be passed), separated by commas. argument at a time.

2. It returns no value or returns void. It returns the value 1.

It displays the outputs of one or more strings The print outputs only the
3. separated by commas. strings.

It is slower than an echo


4. It is comparatively faster than the print statement.
statement.

print_r() Function
The print_r() function is a built-in function in PHP and is used to print or
display information stored in a variable.
Syntax:
print_r( $variable, $isStore )
Parameters: This function accepts two parameters as shown in above syntax
and described below.
1. $variable: This parameter specifies the variable to be printed and
is a mandatory parameter.
2. $isStore: This an option parameter. This parameter is of boolean
type whose default value is FALSE in which case the function simply
prints the value of $variable without returning anything. If this
parameter is set to TRUE then the print_r() function, instead of
printing, will return the output which it is supposed to print. One can
store this output in a variable so as to use it in a meaningful way.

Return Value: If the $variable is an integer or a float or a string the function


prints the value of the variable. If the variable is an array, the function prints
the array in a format which displays the keys as well as values. A similar
notation is used for objects. If the parameter $isStore is set to TRUE then the
print_r() function will return a string containing the information which it is
supposed to print.

Programs given below illustrate the print_r() function:

Program 1:
<?php

// PHP program to illustrate


// the print_r() function

// string variable
$var1 = "Welcome to GeeksforGeeks";

// integer variable
$var2 = 101;

// array variable
$arr = array('0' => "Welcome", '1' => "to", '2' => "GeeksforGeeks");

// printing the variables


print_r($var1);
echo"\n";
print_r($var2);
echo"\n";
print_r($arr);

?>
Output:
Welcome to GeeksforGeeks
101
Array
(
[0] => Welcome
[1] => to
[2] => GeeksforGeeks
)

Program 2:
<?php

// PHP program to illustrate the print_r()


// function when $isStore is set to true

// array variable
$arr = array('0' => "Welcome", '1' => "to",
'2' => "GeeksforGeeks");

// storing output of print_r() function


// in another variable
$results = print_r($arr, true);

echo $results;

?>

Output:
Array
(
[0] => Welcome
[1] => to
[2] => GeeksforGeeks
)

Die() Function
The die() function in PHP is used to print a message and terminate the
current script execution. It is essentially the same as the exit() function,
which is used to halt the execution of a script.
The die() function provides a simple and basic error handling mechanism in
PHP.
Syntax
die($message)

Parameters : This function accepts only one parameter and which is not
mandatory to be passed.
• $message : This parameter represents the message to printed
while exiting from script.
Return Value : It has no return value but prints given message while exiting
the script.
Here are few examples of how the die() function can be used in PHP:
Example 1

<?php

$name = "John";

if ($name != "Jane") {

die("Access denied!");

echo "Welcome, $name!";


?>

In this example, the die() function is used to terminate the script if the value
of the $name variable is not equal to "Jane". If the condition is met and the
function is executed, the message "Access denied!" will be displayed and
the script will terminate without executing the echo statement.

Example 2
<?php
// blank url of site
// so that die() is executed
$site = "";

// open url else die (exit)


fopen($site, "r")
or die("Unable to connect to given site.");
?>

Output :
Unable to connect to given site.

You might also like