[go: up one dir, main page]

100% found this document useful (1 vote)
42 views20 pages

Chapter 05

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

Chapter 05

5.1 Introduction to MySQL- create a database.

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


5.3 Database operations : Insert data, Retrieving the Query result
5.4 Update and delete operations on table data
Introduction to MySQL- create a database.

● 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
Working of mysql database with php
Create database
<?php
$servername = "localhost";
$username = "root";
$password = "";/* Put your password here*/
/* Create connection*/
$conn = mysqli_connect($servername, $username, $password);
/* Check connection*/
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
/* Create database*/
$sql = "CREATE DATABASE stud";
if (mysqli_query($conn, $sql)) {
echo " $sql created successfully";
}else{
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
mysqli_connect(host, username, password, dbname, port, socket)

Parameter Description

host Optional. Specifies a host name or an IP address

username Optional. Specifies the MySQL username

passworda 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


The die():- is an inbuilt function in PHP. It is used to print message and exit from the
current php script. It is equivalent to exit() function in PHP.

Syntax :

die($message)

Parameters : This function accepts only one parameter and which is not mandatory
to be passed.

$message : This parameter represents the message to printed while exiting from
script.
Connection to a Mysql database

Php will work with virtually all database software,including oracle and sybase
but most commonly used is freely available MYSQL database

php 5 and later can work with MYSQL database using:

1)MYSQLi extension(“the “i” stands for improved”),and

2)PDO(php data objects)


PHP Connect to MySQL
Should I Use MySQLi or PDO?
If you need a short answer, it would be "Whatever you like".

● Both MySQLi and PDO have their advantages:


● PDO will work on 12 different database systems, whereas MySQLi will only
work with MySQL databases.
● So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries.
With MySQLi, you will need to rewrite the entire code - queries included.
● Both are object-oriented, but MySQLi also offers a procedural API.
● Both support Prepared Statements. Prepared Statements protect from SQL
injection, and are very important for web application security.
Table Creation

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

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE CO (
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
)";
if (mysqli_query($conn, $sql)) {
echo "$sql successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
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.
Insert data in 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());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>
Retrive and present Data using Select command
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM co";
$result = mysqli_query($conn, $sql);
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);
?>
Update data
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE co SET lastname='chavan', firstname='vaibhav' WHERE id=2";

if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>
Delete Data
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "delete FROM co WHERE id=1";

if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

You might also like