Mysqli Database

You might also like

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

Compiled By: Basanta Chapagain www.basantachapagain.com.

np

Working with Database
When we need to our data for future  we have to use database. Into PHP we 
have different mechanism  to use database.

PHP have direct support with MySQL with mysql and mysqli extension.
We can also use PDO(PHP Data Object) for database connection.

Database Connection

Every time you need to do something that involves a database operation 
(insert, delete, update or select), you need to make a connection to the 
database before you can do anything else.

Syntax for database Connection

connection identifier = mysqli_connect(hostname,database username, 
database password, database name);

Example: 
$link = mysqli_connect(‘localhost’,’root’,’’,’db_college);

Error Check 

If we get error on database connection we will get error number which can be 
accessed by using mysqli_connect_errno() and error message with 
mysqli_connect_error(). So after database connection we need to check.

if(mysqli_connect_errno()) {
  die("Database connection failed" . mysqli_connect_error());
}

or 

if(!$connectionvaribale) {
  die("Database connection failed" . mysqli_connect_error());
}
Compiled By: Basanta Chapagain www.basantachapagain.com.np

Selection of Database [Optional]

To change the database in use, you can use mysqli_select_db().
You will only need this function if your PHP application deals with more than 
one database.

First Connection:
$link = mysqli_connect(‘localhost’,’root’,’’,’db_college’); 

* if you need to change database connection for  database name db_college1

 mysqli_select_db($link, 'db_college1'); 

Closing Database Connection
mysqli_close()
You can use this function to close a MySQL connection. It returns TRUE on 
success and FALSE on failure. 

mysqli_close($link);

Here $link is connection identifier.

Executing Database Query

mysqli_query()

This is the function used for executing MySQL queries. It returns FALSE on 
failure. For SELECT, SHOW, DESCRIBE and EXPLAIN queries (where there is 
an output), it returns a MySQL result set/object (resource). For other query it 
will return true,false only

* mysqli query  is common function to execute query for 
select,insert,update,delete.

Example:

$link = mysqli_connect('localhost', 'root', '', 'db_college');
$query = "SELECT * FROM tbl_student";
$result = mysqli_query($link, $query);
mysqli_close($link);
Compiled By: Basanta Chapagain www.basantachapagain.com.np

Extracting Data From Database

* mysqli_fetch_array()
Syntax: mysqli_fetch_array(result,[restulttype]);
result is result set  and resulttype is optional with following values 
• MYSQLI_ASSOC

• MYSQLI_NUM

• MYSQLI_BOTH [Default Value] 

Default it will return with MYSQLI_BOTH
Example: 
Returns only an Both index and associative array 
mysqli_fetch_array($result, MYSQLI_BOTH);  
or 
mysqli_fetch_array($result);  
Returns only an Indexed array 
mysqli_fetch_array($result, MYSQLI_NUM); 
Returns only an associative array 
mysqli_fetch_array($result, MYSQLI_ASSOC); 
This function is used for reading data from a MySQL result set (returned by a 
mysqli_query() ). It reads and returns one row of data as an array and then 
moves the pointer to next row. When there are no more rows to return, it 
returns NULL. Because of this behavior, it’s often used with a While Loop as 
below.
while ($row = mysqli_fetch_array($result)) {
/* Till there is data, $row will be an array.
 * At the end, $row becomes NULL ending the loop.
 */
}
Compiled By: Basanta Chapagain www.basantachapagain.com.np

Combine Example for connection,select
<?php
$link = mysqli_connect('localhost', 'root', '', 'db_college');
$query = "SELECT id,first_name,last_name FROM tbl_student";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
    echo $row[0] . ': ' . $row[1] . ' ' . $row[2];
}
mysqli_free_result($result);
mysqli_close($link);
?>
When you run, above code will output following content in the web browser is
like: 
1: Ram Thapa
2: Hari Prasad

Similar Functions to access Data.

Same as mysqli_fetch_array($result, MYSQLI_NUM) 
mysqli_fetch_row($result); 
Same as mysqli_fetch_array($result, MYSQLI_ASSOC) 
mysqli_fetch_assoc($result); 

Clearing Result

mysqli_free_result()
Immediately after using a result set, you can free the memory used for it as 
below.
mysqli_free_result($result)
Compiled By: Basanta Chapagain www.basantachapagain.com.np

Finding Status of Query Execution

mysqli_num_rows()
This is used for SELECT query, mysqli_num_rows() returns the number of 
rows in a result set. Using it, you can take a different action when the result 
set is empty. If select query have related data into table then result set get 
value more then 0.
if (mysqli_num_rows($result) > 0) {
    // Proceed with the $result
} else {
    // Show an some message
}
For SELECT, it returns number of rows in the result set as 
mysqli_num_rows().

mysqli_affected_rows()
This function provides information on last MySQL query executed. For 
INSERT, UPDATE, and DELETE, it provides number of rows affected. 
$query = "insert into tbl_user(name,username,password,status) values(‘Ram’, 
‘ram’,’ram’,’1’)"; 
mysqli_query($link, $query); 
if (mysqli_affected_rows($link) == 1) { 
// Rest of the code
 } else { 
// Show an error message
 } 
Compiled By: Basanta Chapagain www.basantachapagain.com.np

Displaying Error Message

mysqli_error()
If there was an error in last MySQL query, this function will return the error. If
there was no error, it would return an empty string.

$query = “select * from tbl_user”;
if (!mysqli_query($link, $query)) {
$logMessage = 'MySQL Error: ' . mysqli_error($link);
     die('There was an error in the query' . $logMessage);
}
Filtering/Escaping Data

mysqli_real_escape_string()
Some characters like single quote has special meaning in SQL statements. For 
an example, single quote is used for wrapping strings. So, if your SQL 
statement contains these special characters, you need to escape them via 
mysqli_real_escape_string() before sending the query to mysqli_query(). 
Following call to mysqli_query() returns FALSE since the single quote in Ram’s
hasn’t been escaped.
Example:
$username = “Ram’s”;
$query = "SELECT id FROM user WHERE username = ’$usenrame’ ";
mysqli_query($link, $query);

Following call to mysqli_query() would return a proper result set (provided 
that an user exists with username Ram’s) since the name is first escaped via 
mysqli_real_escape_string().
Compiled By: Basanta Chapagain www.basantachapagain.com.np

Example : 
$username = “Ram’s”;
$username = mysqli_real_escape_string($link, $username); 
$query = "SELECT id FROM user WHERE username = ’$usenrame’ ";
mysqli_query($link, $query);

If your SQL statements are built based on user inputs like below, it’s always a 
good idea to use this function since user input may contain special characters.
$username = mysqli_real_escape_string($link, $_POST['username']); 
$query = "SELECT `id` FROM `employee` WHERE `username` = 
'$username'"; 
mysqli_query($link, $query); 

You might also like