PHP 5
PHP 5
➢ Introduction to MySQL:
➢ Create Database:
1. Steps using PHP Code: Creating database: With CREATE DATABASE query:
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.
<?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.
<?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
<?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.
<?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:
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:-