0% found this document useful (0 votes)
72 views

PHP 5

Uploaded by

tiwarimanoj1405
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)
72 views

PHP 5

Uploaded by

tiwarimanoj1405
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/ 11

UNIT 5 : DATABASE OPERATIONS

5.1 : Introduction to MySQL - Create a database

➢ Introduction to MySQL:

1. MySQL is an open-source relational database management system.


2. Its name is a combination of “My”, the name of co-founder Michael Widenius’s
daughter, and “SQL”, the abbreviation for Structured Query Language.
3. It is written in C and C++.
4. Datatypes in MySQL :

➢ Create Database:

1. Steps using PHP Code: Creating database: With CREATE DATABASE query:

Step 1: Set variables with values for servername, username, password.


Step 2: Set connection object by passing servername, username, password as parameters.
Step 3: Set query object with the query as "CREATE DATABASE dept";
Step 4: Execute query with connection object.
Code (Optional)-
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);}
$sql = "CREATE DATABASE ifdept";
if ($conn->query($sql) === TRUE){
echo "Database created successfully";}
else{
echo "Error creating database: " . $conn->error;}
$conn->close ();
?>

2. Steps using phpMyAdmin :

Step 1: Click on Start and select XAMPP from the list. Open Xampp control panel by clicking on
the option from the list. The Control Panel is now visible and can be used to initiate or halt the
working of any module.
Step2: Click on the "Start" button corresponding to Apache and MySQL modules. Once it starts
working, the user can see the following screen:
Step 3: Now click on the "Admin" button corresponding to the MySQL module. This automatic
ally redirects the user to web browser to the following address- http://localhost/phpmyadmin
Step 4: Screen with multiple tabs such as Database, SQL, User Accounts, Export, Import,
Settings, etc. Will appear. Click on the "Database" tab. Give an appropriate name for the
Database in the first textbox and click on create option.
Step 5 : In the created Database, click on the 'Structure' tab. Towards the end of the tables list,
the user will see a 'Create Table' option. Give appropriate "Name" and "Number of Columns"
for table and click on 'Go' button.
Step 6 : Give details of columns based on their type. Enter the names for each column, select
the type, and the maximum length allowed for the input field. Click on "Save" in the bottom
right corner. The table with the initialized columns will be created.

5.2 Connecting to a MySQL database : MySQL database server from PHP

➢ Connection Using MySQLi Object Interface:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_close($conn);
?>
Explanation:
1. The first part of the script is three variables (server name, username, and password) and
their respective values.
2. These values should correspond to your connection details.
3. Next is the main PHP function mysqli_connect(). It establishes a connection with the
specified database.
4. When the connection fails, it gives the message Connection failed.
5. The die function prints the message and then exits out of the script If the connection is
successful, it displays “Connected successfully.”
6. When the script ends, the connection with the database also closes. If you want to end
the code manually, use the mysqli_close function.

➢ Connection using MySQLi Procedural interface:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " ;
mysqli_error($conn);
}
mysqli_close($conn);
?>
Explanation:
1. The first part of the script is three variables (server name, username, and password) and
their respective values. These values should correspond to your connection details.
2. Next is the main PHP function mysqli_connect(). It establishes a connection with the
specified database.
3. When the connection fails, it gives the message Connection failed.
4. The die function prints the message and then exits out of the script If the connection is
successful, it displays “Connected successfully.”
5. Next, write a sql statement to create a database. If connection established successfully
then echo "Database created successfully"; else echo "Error creating database: "
6. When the script ends, the connection with the database also closes. If you want to end
the code manually, use the mysqli_close function.
Write a program to connect PHP with MYSQL.

Solution1:

<?php
$servername = "localhost";
$username = "root";
$password = "";
// Connection
$conn = new mysqli($servername,$username, $password);
// For checking if connection issuccessful or not
if ($conn->connect_error)
{
die("Connection failed: ". $conn->connect_error);
}
echo "Connected successfully";
?>
Output:
Connected successfully

OR
➢ Connection using PDO - PHP Data Object:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
try
{
$conn = new PDO("mysql:host=$servername;dbname=myDB",
$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Explanation:
1. The first part of the script is three variables (server name, username, and password) and
their respective values. These values should correspond to your connection details.
2. If a problem arises while trying to connect, it stops running and attempts to catch and
solve the issue. Catch blocks can be set to show error messages or run an alternative code.
3. Following is the setAttribute method adding two parameters to the
PDO:
1. PDO::ATTR_ERRMODE
2. PDO::ERRMODE_EXCEPTION
This method instructs the PDO to run an exception in case a query fails.
Add the echo “Connected successfully.” to confirm a connection is established.
Define the PDOException in the catch block by instructing it to display a message when
the connection fails.
➢ Functions to fetch data from Database:

1. mysqli_fetch_row():
a. This function will fetch data about the single row with which the row pointer currently
exists.
b. After fetching the entire row details, it will be returned as an array with number
indices corresponding to the MySQL field offset.
c. If no results found for the query, then mysqli_fetch_row() will return NULL.
d. Example :
$conn = mysqli_connect("localhost", "root", "test", "blog_samples") or
die("Connection Error: " . mysqli_error($conn));
$query = "SELECT * from Users"; $result = mysqli_query($conn, $query) or
die(mysqli_error($conn));
$row = mysqli_fetch_row($result);
print "<pre>";
print_r($row);
print "<pre>";
Output:Array([0] => 1[1] => admin[2] => admin123[3] => student

2. mysqli_fetch_assoc():
a. This function is similar to the mysqli_fetch_row(), except that, it will return an array of
row information containing column values are indexed with the column name.
b. So the result type is an associative array where each column name and values of a
single row are associated together as name, value pairs.

3. mysqli_fetch_array():
a. This MySQL fetch method returns resultant array with both indices.
b. That is, field offset and field name. So, it would be used most probably by having both
option of indexing.
c. mysqli_fetch_array() accepts an optional argument for specifying resultant array index
type and its possible values are,
• MYSQLI_BOTH – It is the default value that would be taken if no second
argument is provided for this function. It will provide resultant array with both
indices.
• MYSQLI_NUM – With this option, mysqli_fetch_array() will return array with
offset indices as same as mysqli_fetch_row().
• MYSQLI_ASSOC – With this option, mysqli_fetch_array() will return array with
name indices as same as mysqli_fetch_assoc().

4. mysqli_fetch_object():
a. mysqli_fetch_object() function will return MySQL data with same structure as
returned by mysqli_fetch_assoc(), but its type is different.
b. mysqli_fetch_object() returns object where as mysqli_fetch_assoc() returns array.
c. So, the way of accessing these data will also be differed.
d. echo $row->user_name;
5. mysqli_fetch_lengths():
a. It is used to returns the length of the fields in the result.
b. It returns an array of integer that represents the size of each column or FALSE if fails.
c. Parameter: Result: It specifies the result set identifier returned by mysqli_query(),
mysqli_store_result() or mysqli_use_result()
d. Example :
<?php
$link = mysqli_connect("localhost","my_user", "my_password", "world");
$query = "SELECT * from Country ORDER BY Code LIMIT 1";
if ($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_row($result);
foreach (mysqli_fetch_lengths($result) as $i => $val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}

6. mysqli_fetch_field():
a. It is used to retrieve the next field in the result set.
b. Returns the definition of one column of a result set as an object. Call this function
repeatedly to retrieve information about all columns in the result set.
c. Returns an object which contains field definition information or false if no field
information is available
d.

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";
if ($result = mysqli_query($link, $query)) {
while ($finfo = mysqli_fetch_field($result)) {
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
4.3 Database Operations : Insert data and retrieving the query result

➢ Insert data :

<?php
require_once 'login.php';
$conn = newmysqli($hostname,$username, $password,$dbname);
$query = "INSERT INTO studentinfo(rollno,name,percentage)
VALUES
('CO103','Yogita Khandagale',98.45)";
$result = $conn->query($query);
if (!$result)
die ("Database access failed: " . $conn->error);
else
echo "record inserted successfully";
?>

Output:
record inserted successfully

➢ Retrieve the query result :

<?php
$con=mysqli_connect('localhost','root','','practical') or die("Connection Failed");
$result=mysqli_query($con,"select username, password from login");
while($row=mysqli_fetch_assoc($result))
{
echo"User name: ".$row['username'];
echo"<br>";
echo"Password : ".$row['password'];
echo"<br><br>";
}
mysqli_close($con);
?>
➢ Insert data and Retrieve the query result :

<?php
$con = mysqli_connect('localhost', 'root', '', 'class');
# Connecting to Database
$query = "insert into user values(1, 'Amit')";
# Inserting Values
$result = mysqli_query($con, $query);
if($result) {
echo 'Insertion Successful <br>';
}
else {
echo 'Insertion Unsuccessful <br>';
}
$query = "select * from user";
# Retrieving Values
$result = mysqli_query($con, $query);
foreach($result as $r) {
echo $r['roll_number'].' '.$r['name'];
}
?>
Output
Insertion Successful
1 Amit

Explanation

The above code connects with a database named „class‟‟. The exam database has a table
named „user‟ with 2 columns roll_number and name.
It executes an insert query on the user and checks whether the insertion was successful or not.
It executes a select query on the user and displays the information retrieved.

4.4 Update and Delete Operations

Explain queries to update and delete data in the database.

Update data : UPDATE query


Update command is used to change / update new value for field in row of table. It updates the
value in row that satisfy the criteria given in query.
The UPDATE query syntax:
UPDATE Table_name SET field_name=New_value WHERE field_name=existing_value
Example :
UPDATE student SET rollno=4 WHERE name='abc'
In the above query, a value from rollno field from student table is
updated with new value as 4 if its name field contains name as ‘abc’.
Delete data: DELETE query
Delete command is used to delete rows that are no longer required from the database tables.
It deletes the whole row from the table.
The DELETE query syntax:
DELETE FROM table_name WHERE some_column = some_value [WHERE condition] is
optional. The WHERE clause specifies which record or records that should be deleted. If the
WHERE clause is not used, all records will be deleted.
Example :-
$sql = "DELETE FROM student WHERE rollno=2";
In the above query, a row from student table is deleted if rollno field
contains 2 in that row.

➢ Updating data in database table:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ifdept";
$conn = new mysqli($servername, $username, $password,
$dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE student SET rollno=4 WHERE
name='abc'";
if ($conn->query($sql) === TRUE)
{
echo "Record updated successfully";
} else
{
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
➢ Deleting data in database table:

Assume Following Table

Database Name-student
Table name - pridata

<?php
$server='localhost';
$username='root';
$password='';
$con=mysqli_connect($server,$username,$password);
if(!$con){
die("Connection to this database failed due to"
.mysqli_connect_error($mysqli));
}
$sql="DELETE FROM student.pridataWHERE name='amit'";
if($con->query($sql)==true){
echo "Record deleted successfully";
}
else{
"ERROR:error".$con->error();
}
$con->close();
?>
Output:-

You might also like