PHP MySQL Notes
PHP MySQL Notes
Syntax
connection mysql_connect($server,$user,$passwd,$new_link,$client_flag);
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.
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 ");
}
?>
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());
}
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");
<?php
$con = new mysqli("localhost", "root", "password", "mydb");
print("Data Created......");
//Closing the connection
$res = $con -> close();
?>
Example
Following example prints the results of INSERT and SELECT queries −
<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");
Example
Assume that we have created a table ‘Players’ in the database and populated it as
shown below −
<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");
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:
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).
Example 1:
Retrieval of row as an associative array using mysqli_fetch_array():
<?php
$con = mysqli_connect("localhost", "root", "password", "mydb");
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");
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");
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
<?php
echo "Hello,This is a display string example!";
?>
Output:
Hello,This is a display string example!
Output:
Multiple argument string!
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.
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
Output:
Hello, World!
10+20=30
It displays the outputs of one or more strings The print outputs only the
3. separated by commas. strings.
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.
Program 1:
<?php
// string variable
$var1 = "Welcome to GeeksforGeeks";
// integer variable
$var2 = 101;
// array variable
$arr = array('0' => "Welcome", '1' => "to", '2' => "GeeksforGeeks");
?>
Output:
Welcome to GeeksforGeeks
101
Array
(
[0] => Welcome
[1] => to
[2] => GeeksforGeeks
)
Program 2:
<?php
// array variable
$arr = array('0' => "Welcome", '1' => "to",
'2' => "GeeksforGeeks");
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!");
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 = "";
Output :
Unable to connect to given site.