0% found this document useful (0 votes)
8 views15 pages

Olpt2 Chapter 6

The document provides an overview of MySQLi, an improved extension for PHP to interact with MySQL databases, highlighting its features such as support for prepared statements, transactions, and enhanced debugging. It includes examples of connecting to a MySQL database, creating and dropping databases, and managing tables using PHP scripts. The document serves as a tutorial for using MySQLi in a PHP environment, detailing syntax and providing practical code examples.

Uploaded by

sammagtira2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

Olpt2 Chapter 6

The document provides an overview of MySQLi, an improved extension for PHP to interact with MySQL databases, highlighting its features such as support for prepared statements, transactions, and enhanced debugging. It includes examples of connecting to a MySQL database, creating and dropping databases, and managing tables using PHP scripts. The document serves as a tutorial for using MySQLi in a PHP environment, detailing syntax and providing practical code examples.

Uploaded by

sammagtira2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

CHAPTER 6: MySQLi PART1

Objectives:
a. Discuss the overview of MySQLi.
b. Recognize the syntax for managing a database.
c. Create a database connection using MySQLi.

Lesson 1: MySQLi Overview


MySQLi is an extension to MySQL API available in PHP and is introduced from PHP 5.0
onwards. It is also known as MySQL improved extension. Motivation behind MySQLi was to take
advantage of new features available in MySQL 4.1.3 onwards. It provides numerous benefits over
MySQL extension.
• MySQL provides an object oriented interface. It provides both object oriented and
procedural approach to handle database operations.
Object Oriented Interface
<?php
$mysqli = mysqli_connect("localhost", "user", "password", "database-name");
$result = mysqli_query($mysqli, "SELECT 'Welcome to MySQLi' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($result);
echo $row['_msg'];
?>
Procedural Approach
<?php
$mysqli = new mysqli("localhost", "user", "password", "database-name");
$result = $mysqli→query("SELECT 'Welcome to MySQLi' AS _msg FROM DUAL");
$row = $result→fetch_assoc();
echo $row['_msg'];
?>

Page | 1
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

• MySQLi supports prepared statments.


• MySQLi supports multiple statments.
• MySQLi supports transactions.
• MySQLi provides enhanced debugging capabilities.
MySQL works very well in combination of various programming languages like PERL, C, C++,
JAVA and PHP. Out of these languages, PHP is the most popular one because of its web
application development capabilities.
This tutorial focuses heavily on using MySQL in a PHP environment. If you are interested in MySQL
with PERL, then you can consider reading the PERL Tutorial.
PHP provides various functions to access the MySQL database and to manipulate the data records
inside the MySQL database. You would require to call the PHP functions in the same way you call
any other PHP function.
The PHP functions for use with MySQL have the following general format −
mysqli function(value,value,...);
The second part of the function name is specific to the function, usually a word that describes
what the function does. The following are two of the functions, which we will use in our tutorial

$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
mysqli→query(,"SQL statement");
The following example shows a generic syntax of PHP to call any MySQL function.
<html>
<head>
<title>PHP with MySQL</title>
</head>
<body>
<?php
$retval = mysqli - > <i>function</i>(value, [value,...]);
if( !$retval ) {
die ( "Error: a related error message" );

Page | 2
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

}
// Otherwise MySQL or PHP Statements
?>
</body>
</html>
MySQL Connection Using PHP Script
PHP provides mysqli contruct or mysqli_connect() function to open a database connection. This
function takes six parameters and returns a MySQL link identifier on success or FALSE on failure.
Syntax
$mysqli = new mysqli($host, $username, $passwd, $dbName, $port, $socket);

Sr.No. Parameter & Description

1 $host
Optional − The host name running the database server. If not specified, then the default
value will be localhost:3306.

2 $username
Optional − The username accessing the database. If not specified, then the default will be
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 the
default will be an empty password.

4 $dbName
Optional − database name on which query is to be performed.

5 $port
Optional − the port number to attempt to connect to the MySQL server..

Page | 3
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

6 $socket
Optional − socket or named pipe that should be used.

You can disconnect from the MySQL database anytime using another PHP function close().
Syntax
$mysqli→close();
Example
Try the following example to connect to a MySQL server −
Copy and paste the following example as mysql_example.php −
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass);

if($mysqli→connect_errno ) {
printf("Connect failed: %s<br />", $mysqli→connect_error);
exit();
}
printf('Connected successfully.<br />');
$mysqli→close();
?>
</body>
Page | 4
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

</html>
Output
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.

For more info about MySQLi Overview, please click the link below:
https://www.youtube.com/watch?v=BEbKji_pSZM

Lesson 2: Creating and Drop Database


Create Database Using mysqladmin
You would need special privileges to create or to delete a MySQL database. So assuming you have
access to the root user, you can create any database using the mysql mysqladmin binary.
Example
Here is a simple example to create a database called TUTORIALS −
[root@host]# mysqladmin -u root -p create TUTORIALS
Enter password:******
This will create a MySQL database called TUTORIALS.
Create a Database using PHP Script
PHP uses mysqli query() or mysql_query() function to create or delete a MySQL database. This
function takes two parameters and returns TRUE on success or FALSE on failure.
Syntax
$mysqli→query($sql,$resultmode)

Sr.No. Parameter & Description

1 $sql
Required - SQL query to create a MySQL database.

2 $resultmode

Page | 5
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending


on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

Example
Try the following example to create a database −
Copy and paste the following example as mysql_example.php −
<html>
<head><title>Creating MySQL Database</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass);

if($mysqli→connect_errno ) {
printf("Connect failed: %s<br />", $mysqli→connect_error);
exit();
}
printf('Connected successfully.<br />');

if ($mysqli→query("CREATE DATABASE TUTORIALS")) {


printf("Database TUTORIALS created successfully.<br />");
}
if ($mysqli→errno) {
printf("Could not create database: %s<br />", $mysqli→error);
}

Page | 6
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

$mysqli→close();
?>
</body>
</html>
Output
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Database TUTORIALS created successfully.
Drop a Database using mysqladmin
You would need special privileges to create or to delete a MySQL database. So, assuming you
have access to the root user, you can create any database using the mysql mysqladmin binary.
Be careful while deleting any database because you will lose your all the data available in your
database.
Here is an example to delete a database(TUTORIALS) created in the previous chapter −
[root@host]# mysqladmin -u root -p drop TUTORIALS
Enter password:******
This will give you a warning and it will confirm if you really want to delete this database or not.
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.

Do you really want to drop the 'TUTORIALS' database [y/N] y


Database "TUTORIALS" dropped
Drop Database using PHP Script
PHP uses mysqli query() or mysql_query() function to drop a MySQL database. This function
takes two parameters and returns TRUE on success or FALSE on failure.
Syntax
$mysqli→query($sql,$resultmode)

Page | 7
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

Sr.No. Parameter & Description

1 $sql
Required - SQL query to drop a MySQL database.

2 $resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending
on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

Example
Try the following example to drop a database −
Copy and paste the following example as mysql_example.php −
<html>
<head><title>Dropping MySQL Database</title></head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass);

if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);
exit();
}
printf('Connected successfully.<br />');

if ($mysqli->query("Drop DATABASE TUTORIALS")) {


printf("Database TUTORIALS dropped successfully.<br />");

Page | 8
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

}
if ($mysqli->errno) {
printf("Could not drop database: %s<br />", $mysqli->error);
}
$mysqli->close();
?>
</body>
</html>
Output
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Database TUTORIALS dropped successfully.

For more info about Creating and Drop Database, please click the link below:
https://www.youtube.com/watch?v=2SYFnVenxRw

Lesson 3: Managing Database and Tables


Once you get connected with the MySQL server, it is required to select a database to
work with. This is because there might be more than one database available with the MySQL
Server.
Selecting MySQL Database from the Command Prompt
It is very simple to select a database from the mysql> prompt. You can use the SQL
command use to select a database.
Example
Here is an example to select a database called TUTORIALS −
[root@host]# mysql -u root -p
Enter password:******
mysql> use TUTORIALS;
Database changed

Page | 9
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

mysql>
Now, you have selected the TUTORIALS database and all the subsequent operations will be
performed on the TUTORIALS database.
NOTE − All the database names, table names, table fields name are case sensitive. So you would
have to use the proper names while giving any SQL command.
Selecting a MySQL Database Using PHP Script
PHP uses mysqli_select_db function to select the database on which queries are to be
performed. This function takes two parameters and returns TRUE on success or FALSE on
failure.
Syntax
mysqli_select_db ( mysqli $link , string $dbname ) : bool

Sr.No. Parameter & Description

1 $link
Required - A link identifier returned by mysqli_connect() or mysqli_init().

2 $dbname
Required - Name of the database to be connected.

Example
Try the following example to select a database −
Copy and paste the following example as mysql_example.php −
<html>
<head>
<title>Selecting MySQL Database</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';

Page | 10
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

$dbpass = 'root@123';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysqli_error($conn));
}
echo 'Connected successfully<br />';

$retval = mysqli_select_db( $conn, 'TUTORIALS' );

if(! $retval ) {
die('Could not select database: ' . mysqli_error($conn));
}
echo "Database TUTORIALS selected successfully\n";
mysqli_close($conn);
?>
</body>
</html>
Output
Access the mysql_example.php deployed on apache web server and verify the output.
Database TUTORIALS selected successfully
Create Table
To begin with, the table creation command requires the following details −
• Name of the table
• Name of the fields
• Definitions for each field
Syntax

Page | 11
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

Here is a generic SQL syntax to create a MySQL table −


CREATE TABLE table_name (column_name column_type);
Now, we will create the following table in the TUTORIALS database.
create table tutorials_tbl(
tutorial_id INT NOT NULL AUTO_INCREMENT,
tutorial_title VARCHAR(100) NOT NULL,
tutorial_author VARCHAR(40) NOT NULL,
submission_date DATE,
PRIMARY KEY ( tutorial_id )
);
Here, a few items need explanation −
• Field Attribute NOT NULL is being used because we do not want this field to be NULL.
So, if a user will try to create a record with a NULL value, then MySQL will raise an error.
• Field Attribute AUTO_INCREMENT tells MySQL to go ahead and add the next available
number to the id field.
• Keyword PRIMARY KEY is used to define a column as a primary key. You can use
multiple columns separated by a comma to define a primary key.
Creating Tables from Command Prompt
It is easy to create a MySQL table from the mysql> prompt. You will use the SQL
command CREATE TABLE to create a table.
Example
Here is an example, which will create tutorials_tbl −
root@host# mysql -u root -p
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> CREATE TABLE tutorials_tbl(
→ tutorial_id INT NOT NULL AUTO_INCREMENT,

Page | 12
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

→ tutorial_title VARCHAR(100) NOT NULL,


→ tutorial_author VARCHAR(40) NOT NULL,
→ submission_date DATE,
→ PRIMARY KEY ( tutorial_id )
→ );
Query OK, 0 rows affected (0.16 sec)
mysql>
NOTE − MySQL does not terminate a command until you give a semicolon (;) at the end of SQL
command.
Creating Tables Using PHP Script
PHP uses mysqli query() or mysql_query() function to create a MySQL table. This function takes
two parameters and returns TRUE on success or FALSE on failure.
Syntax
$mysqli→query($sql,$resultmode)

Sr.No. Parameter & Description

1 $sql
Required - SQL query to create a MySQL table.

2 $resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending
on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

Example
Try the following example to create a table −
Copy and paste the following example as mysql_example.php −
<html>
<head>
<title>Creating MySQL Table</title>

Page | 13
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if($mysqli→connect_errno ) {
printf("Connect failed: %s<br />", $mysqli→connect_error);
exit();
}
printf('Connected successfully.<br />');

$sql = "CREATE TABLE tutorials_tbl( ".


"tutorial_id INT NOT NULL AUTO_INCREMENT, ".
"tutorial_title VARCHAR(100) NOT NULL, ".
"tutorial_author VARCHAR(40) NOT NULL, ".
"submission_date DATE, ".
"PRIMARY KEY ( tutorial_id )); ";
if ($mysqli→query($sql)) {
printf("Table tutorials_tbl created successfully.<br />");
}
if ($mysqli→errno) {
printf("Could not create table: %s<br />", $mysqli→error);
}

Page | 14
MODULE INTEGRATIVE PROGRAMMING TECHNOLOGIES - 2

$mysqli→close();
?>
</body>
</html>
Output
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Table tutorials_tbl created successfully.

For more info about Tables, please click the link below:
https://www.youtube.com/watch?v=zYNAfEHGXAg

REFERENCES
https://www.tutorialspoint.com/mysqli/mysqli_introduction.htm
https://www.tutorialspoint.com/mysqli/mysqli_php_syntax.htm
https://www.tutorialspoint.com/mysqli/mysqli_create_database.htm
https://www.tutorialspoint.com/mysqli/mysqli_select_database.htm
https://www.tutorialspoint.com/mysqli/mysqli_create_tables.htm

Page | 15

You might also like