Professional Documents
Culture Documents
UNIT - 5
UNIT - 5
What is MySQL?
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL uses standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle
Corporation
MySQL is named after co-founder Monty Widenius's daughter: My
Employees
Products
Customers
Orders
Database Queries
A query is a question or a request.
o mysqli_connect()
o PDO::__construct()
PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database. It
returns resource if connection is established or null.
Syntax
1. resource mysqli_connect (server, username, password)
PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It
returns true if connection is closed or false.
Syntax
1. bool mysqli_close(resource $resource_link)
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..
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></html>
Output
Access the mysql_example.php deployed on apache web server and verify
the output.
Connected successfully.
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
The data type specifies what type of data the column can hold. For a
complete reference of all the available data types, go to our Data Types
reference.
After the data type, you can specify other optional attributes for each
column:
NOT NULL - Each row must contain a value for that column, null
values are not allowed
DEFAULT value - Set a default value that is added when no other
value is passed
UNSIGNED - Used for number types, limits the stored data to
positive numbers and zero
AUTO INCREMENT - MySQL automatically increases the value of the
field by 1 each time a new record is added
PRIMARY KEY - Used to uniquely identify the rows in a table. The
column with PRIMARY KEY setting is often an ID number, and is
often used with AUTO_INCREMENT
Each table should have a primary key column (in this case: the "id"
column). Its value must be unique for each record in the table.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
PHP & MySQL - Select Database Example
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
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';
$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.
The INSERT INTO statement is used to add new records to a MySQL table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies
which record or records that should be deleted. If you omit the WHERE clause, all
records will be deleted!
The following examples delete the record with id=3 in the "MyGuests"
table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
After the record is deleted, the table will look like this:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies
which record or records that should be updated. If you omit the WHERE clause, all
records will be updated!
The following examples update the record with id=2 in the "MyGuests"
table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
After the record is updated, the table will look like this:
The following example shows the same as the example above, in the
MySQLi procedural way:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
SQL Joins
A JOIN clause is used to combine rows from two or more tables, based on
a related column between them.
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Notice that the "CustomerID" column in the "Orders" table refers to the
"CustomerID" in the "Customers" table. The relationship between the two
tables above is the "CustomerID" column.
Then, we can create the following SQL statement (that contains an INNER
JOIN), that selects records that have matching values in both tables:
Example