0% found this document useful (0 votes)
14 views26 pages

PHP JT unit4

This document provides an overview of accessing MySQL databases using phpMyAdmin and PHP MySQLi functions. It covers installation requirements, various SQL commands for creating, updating, deleting, and selecting data from databases, as well as functions for managing database connections. Additionally, it explains the client-server architecture of MySQL and includes code examples for practical implementation.

Uploaded by

dhanrajbhandge00
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)
14 views26 pages

PHP JT unit4

This document provides an overview of accessing MySQL databases using phpMyAdmin and PHP MySQLi functions. It covers installation requirements, various SQL commands for creating, updating, deleting, and selecting data from databases, as well as functions for managing database connections. Additionally, it explains the client-server architecture of MySQL and includes code examples for practical implementation.

Uploaded by

dhanrajbhandge00
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/ 26

Unit-4 Accessing MySQL

● As we know that, any simple website or application needs interaction


with data or data management, so it uses databases phpMyAdmin has
become one of the popular, free, open-source software platforms for
administration of MySQL and MariaDB data over the web world.
● This tool is primarily written in PHP for web hosting and related
services.

phpMyAdmin is the most trusted and user-friendly database manager and


mostly used for web-based applications or programs.
phpMyAdmin: To install phpMyAdmin software, you need a server
running platform like Windows or Linux supporting operating systems.
● Web Browser: You need a web browser interface to run the tool.
● PHP scripting language: You need a server side language.
● Apache Web server: You need a web server to store phpMyAdmin files.
● MySQL or MariaDB Database: You need a database to manage
application data.
Note: XAMPP package installation is the easiest way to get the
phpMyAdmin tool.

PHP MySQLi Introduction


● The MySQLi functions allow you to access MySQL database servers.
Installation / Runtime Configuration
● For the MySQLi functions to be available, you must compile PHP with
support for the MySQLi extension.

MySQL Commands:
1. MySQL Create Database
● create database db1;
● The CREATE DATABASE statement is used to create a database
in MySQL.
● The following examples create a database named "myDB":
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

2) MySQL Create Query



● The CREATE TABLE statement is used to create a table in
MySQL.
● We will create a table named "MyGuests", with five columns:
"id", "firstname", "lastname", "email" and "reg_date":
● CREATE TABLE customers (id int(10), name varchar(50), city
varchar(50), PRIMARY KEY (id ) );

CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP)

3) MySQL Insert Query


● After a database and a table have been created, we can start
adding data in them.
● Here are some syntax rules to follow:
● The SQL query must be quoted in PHP
● String values inside the SQL query must be quoted
● Numeric values must not be quoted
● The word NULL must not be quoted
● The INSERT INTO statement is used to add new records to a
MySQL table:
● INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

4) MySQL Update Query


● The UPDATE statement is used to update existing records in a
table:
● UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

id firstname lastname email reg_date


1 John Doe [email protected] 2014-10-22 14:26:15

2 Mary Moe [email protected] 2014-10-23 10:22:30


m

The following examples update the record with id=2 in the "MyGuests"
table:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

5) MySQL Delete Query


● The DELETE statement is used to delete records from a table:
● DELETE FROM table_name
WHERE some_column = some_value

id firstname lastname email reg_date

1 John Doe [email protected] 2014-10-22 14:26:15

2 Mary Moe [email protected] 2014-10-23 10:22:30

3 Julie Dooley [email protected] 2014-10-26 10:48:23

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 = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>
6) MySQL Select Query
● The SELECT statement is used to select data from one or more
tables:
● SELECT column_name(s) FROM table_name
● or we can use the * character to select ALL columns from a
table:
● SELECT * FROM table_name

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

7)Insert Multiple Records


● Multiple SQL statements must be executed with the
mysqli_multi_query() function.
● The following examples add three new records to the
"MyGuests" table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";

if ($conn->multi_query($sql) === TRUE) {


echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

8) where Query:
● The WHERE clause is used to filter records.
● The WHERE clause is used to extract only those records that
fulfill a specified condition.
● SELECT column_name(s) FROM table_name WHERE
column_name operator value
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE


lastname='Doe'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Database Handling Using PHP with MySQL
● MySQL is a relational database management system based on the
Structured Query Language,
● which is the popular language for accessing and managing the
records in the database.
● MySQL is open-source and free software under the GNU license.
It is supported by Oracle Company.
Database :
● A database is an application that stores the organized collection
of records.
● It can be accessed and managed by the user very easily.
● It allows us to organize data into tables, rows, columns, and
indexes to find the relevant information very quickly.
● MySQL is currently the most popular database management
system software used for managing the relational database.
● It is open-source database software,with relevant information
very quickly.
MySQL Works
● MySQL follows the working of Client-Server Architecture.
● This model is designed for the end users called clients to access
the resources from a central computer known as a server using
network services.
● Here, the clients make requests through a graphical user interface
(GUI), and the server will give the desired output as soon as the
instructions are matched.
● The process of MySQL environment is the same as the
client-server model
Functions in Mysql:

1. PHP mysqli change_user() Function


Definition and Usage
● The change_user() / mysqli_change_user() function changes the user of
the specified database connection, and sets the current database.
Syntax:
Object oriented style:
● $mysqli -> change_user(username, password, dbname)
Procedural style:
● mysqli_change_user(connection, username, password, dbname)

Parameter Values
Parameter Description
connection Required. Specifies the MySQL connection to use
username Required. Specifies the MySQL user name
password Required. Specifies the MySQL password
dbname Required. Specifies the database to change
Example - Object Oriented style
● Change the user of the specified database connection:

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}

// Reset all and select a new database


mysqli_change_user($con, "my_user", "my_password", "test");

mysqli_close($con);
?>

2. PHP mysqli close() Function


Definition and Usage
● The close() / mysqli_close() function closes a previously opened
database connection.

Syntax:
Object oriented style:
$mysqli -> close()
Procedural style:
mysqli_close(connection)
Parameter Values

Parameter Description
connection: Required. Specifies the MySQL connection to
close

Example - Object Oriented style


● Close a previously opened database connection:

<?php
$mysqli = new
mysqli("localhost","my_user","my_password","my_db");

if ($mysqli -> connect_errno)


{
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
// ....some PHP code...

$mysqli -> close();


?>

3. PHP mysqli connect() Function


Definition and Usage
● The connect() / mysqli_connect() function opens a new
connection to the MySQL server.

Syntax
Object oriented style:
$mysqli -> new mysqli(host, username, password, dbname, port, socket)
Procedural style:
mysqli_connect(host, username, password, dbname, port, socket)

Parameter Values
Parameter Description
host Optional. Specifies a host name or an IP address
username Optional. Specifies the MySQL username
password Optional. Specifies the MySQL password
dbname Optional. Specifies the default database to be
used
port Optional. Specifies the port number to attempt to
connect to the MySQL server
socket Optional. Specifies the socket or named pipe to
be used

Example - Object Oriented style


● Open a new connection to the MySQL server:

<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");

// Check connection
if ($mysqli -> connect_errno)
{
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
?>

4. PHP mysqli connect_errno() Function:


Definition and Usage
● The connect_errno / mysqli_connect_errno() function returns the
error code from the last connection error, if any.

Syntax:

Object oriented style:


$mysqli -> connect_errno
Procedural style:
mysqli_connect_errno()

Example - Object Oriented style


● Return an error code from the last connection error, if any:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");

// Check connection
if ($mysqli -> connect_errno)
{
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
?>

5. PHP mysqli select_db() Function

Definition and Usage


● The select_db() / mysqli_select_db() function is used to change
the default database for the connection.

Syntax
Object oriented style:
$mysqli -> select_db(name)
Procedural style:
mysqli_select_db(connection, name)

Parameter Description
connection Required. Specifies the MySQL connection to use
name Required. Specifies the database name
Example - Object Oriented style
● Change the default database for the connection:

<?php
$mysqli = new
mysqli("localhost","my_user","my_password","my_db");

if ($mysqli -> connect_errno) {


echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}

// Return name of current default database


if ($result = $mysqli -> query("SELECT DATABASE()")) {
$row = $result -> fetch_row();
echo "Default database is " . $row[0];
$result -> close();
}

// Change db to "test" db
$mysqli -> select_db("test");

// Return name of current default database


if ($result = $mysqli -> query("SELECT DATABASE()")) {
$row = $result -> fetch_row();
echo "Default database is " . $row[0];
$result -> close();
}
$mysqli -> close();
?>
PHP MySQL Connect and Selecting the Database mysql_connect()
● PHP mysql_connect() function is used to connect with MySQL
databases.
● It returns resources if connection is established or null.
Connection to MySQL
● Before we can access data in the MySQL database, we need to be able
to connect to the server:
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

● Example: To connect Mysql and create Database “Newdb”

<?php
// Database configuration
$servername = "localhost"; // Change this to your database
$username = "root"; // Change this to your database username
$password = ""; // Change this to your database password
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS Newdb1"; //
Change 'my_database' to your desired database name
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// Close connection
$conn->close();
?>

Example: Selecting the database.

<?php
// Database configuration
$servername = "localhost"; // Change this to your database server
$username = "root"; // Change this to your database username
$password = ""; // Change this to your database password
$database = "Newdb"; // Change this to your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Selecting DB
$conn->select_db($database);
// Close connection
mysqli_close($con);
?>

Executing Simple Queries:

<?php
// Database configuration
$servername = "localhost"; // Change this to your database server
$username = "root"; // Change this to your database username
$password = ""; // Change this to your database password
$database = "Newdb"; // Change this to your database name
// Create connection
$conn = new mysqli($servername, $username, $password,
$database); // Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL to create table
$sql = "CREATE TABLE IF NOT EXISTS users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP )";
// Execute SQL query
if ($conn->query($sql) === TRUE) {
echo "Table users created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Close connection
$conn->close();
?>

Retrieving Query Results


● PHP mysql_query() function is used to execute select query.
Since PHP 5.5, mysql_query() function is deprecated.
● There are two other MySQLi functions used in select query.
● mysqli_num_rows(mysqli_result $result): returns number of
rows.
● mysqli_fetch_assoc(mysqli_result $result): returns row as an
associative array.
● Each key of the array represents the column name of the table. It
returns NULL if there are no more rows.
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn)
{
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$sql = 'SELECT * FROM emp4';
$retval=mysqli_query($conn, $sql);
if(mysqli_num_rows($retval) > 0)
{
while($row = mysqli_fetch_assoc($retval))
{
echo "EMP ID :{$row['id']} <br> ".
"EMP NAME : {$row['name']} <br> ".
"EMP SALARY : {$row['salary']} <br> ".
"--------------------------------<br>";
} //end of while
}
else
{
echo "0 results";
}
mysqli_close($conn);
?>

Mysql Counting Query:


● To count the number of returned records after executing a select query
in PHP, you can use the COUNT SQL function or count the rows in
the result set

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT count(*) as count from emp where id=101”


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

MySQL Update Query


● The UPDATE statement is used to update existing records in a
table:
● UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

id firstname lastname email reg_date


1 John Doe [email protected] 2014-10-22 14:26:15

2 Mary Moe [email protected] 2014-10-23 10:22:30


m

The following examples update the record with id=2 in the "MyGuests"
table:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

You might also like