PHP_CH_05
PHP_CH_05
MySQL is the most popular database system used with the PHP language.
What is MySQL
MySQL is one of the most popular relational database system being used on the Web today. It is
freely available and easy to install, however if you have installed XAMPP it already there on your
machine. MySQL database server offers several advantages:
MySQL is easy to use, yet extremely powerful, fast, secure, and scalable.
MySQL runs on a wide range of operating systems, including UNIX or Linux, Microsoft
Windows, Apple Mac OS X, and others.
MySQL supports standard SQL (Structured Query Language).
MySQL is ideal database solution for both small and large applications.
MySQL is developed, and distributed by Oracle Corporation.
MySQL includes data security layers that protect sensitive data from intruders.
MySQL database stores data into tables like other relational database. A table is a collection of
related data, and it is divided into rows and columns.
Each row in a table represents a data record that are inherently connected to each other such as
information related to a particular person, whereas each column represents a specific field such
as id, first_name, last_name, email, etc. The structure of a simple MySQL table that contains person's
general information may look something like this:
+----+------------+-----------+----------------------------------+
| id | first_name | last_name | email |
+----+------------+-----------+----------------------------------+
| 1 | Peter | Parker | peterparker@mail.com |
| 2 | John | Rambo | johnrambo@mail.com |
| 3 | Clark | Kent | clarkkent@mail.com |
| 4 | John | Carter | johncarter@mail.com |
| 5 | Harry | Potter | harrypotter@mail.com |
+----+------------+-----------+----------------------------------+
SQL, the Structured Query Language, is a simple, standardized language for communicating with
relational databases like MySQL. With SQL you can perform any database-related task, such as
creating databases and tables, saving data in database tables, query a database for specific records,
deleting and updating data in databases.
Connecting to MySQL Database Server
mysqli ()
In order to store or access the data inside a MySQL database, you first need to connect to the
MySQL database server. In PHP you can easily do this using the mysqli () function.
All communication between PHP and the MySQL database server takes place through this
connection.
Syntax:
$conn = new mysqli("hostname", "username", "password", "database");
The hostname parameter in the above syntax specify the host name (e.g. localhost), or
IP address of the MySQL server, whereas the username and password parameters specifies
the credentials to access MySQL server, and the database parameter specify the default
MySQL database to be used when performing queries.
die()
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)
where message is a Required Parameter. It specifies the message or status number to write before
exiting the script.
connect_error()
connect_error() function returns the error description from the last connection error, if any.
Syntax
$conn -> connect_error
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database="myDB";
// Create connection
$conn = new mysqli($servername, $username, $password,$database);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// 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 studentrecord";
if ($conn->query($sql) === TRUE)
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
We will create a table named " STUDENT ", with columns: " roll ", "firstname", "lastname", "email"
Description:
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. Its value must be unique for each record in the table.
Program to create table student in studentrecord database
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentrecord";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Insert Data
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,...)
Note: If a column is AUTO_INCREMENT (like the "roll" column), it is no need to be specified in the SQL
query; MySQL will automatically add the value.
Example
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentrecord";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Insert Multiple Records Into MySQL
Multiple SQL statements must be executed with the multi_query() function.
Note that each SQL statement must be separated by a semicolon.
Example
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentrecord";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Select & Display Data From Your MYSQL DATABASE
The following example selects the all records from the student table and displays it on the page:
First, we set up the SQL query that selects the all records.
The next line of code runs the query and puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through.
The while() loop loops through the result set and outputs the data from the id, firstname and
lastname columns.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentrecord";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM student ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo "roll: " . $row["roll"]. " - firstname: " . $row["firstname"]. " - lastname: " . $row["lastname"]. " -
email: ".$row["email"]."<br>";
}
}
else
{
echo "0 results";
}
$conn->close();
?>
Select and Filter Data From a MySQL Database
The WHERE clause is used to filter records.
The WHERE clause is used to extract only those records that fulfill a specified condition.
The following example selects the roll, firstname and lastname columns from the student table where
the lastname is "somwanshi", and displays it on the page:
Example 1:-
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentrecord";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Example2:- SELECT column_name(s) FROM table_name WHERE column_name operator value
SELECT * FROM student WHERE lastname='somwanshi'
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentrecord";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Delete Data From a MySQL Table
The DELETE statement is used to delete records from a table:
DELETE FROM table_name WHERE some_column = some_value
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 roll=2 in the "student" table:
Example
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentrecord";
// 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 student WHERE roll=2";
The WHERE clause specifies which record or records that should be updated. If you omit the WHERE
clause, all records will be updated!
Example
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentrecord";
// 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
$conn->close();
?>
Submitting form data to Database:
Form1.html
<html>
<body>
<form name="form1" action="Demo.php" method="POST">
Enter First name: <br> <input type="text" name="FNAME"> <br><br>
Enter Last name: <br> <input type="text" name="LNAME"> <br><br>
Enter Email Id : <br> <input type="Email" name="EMAIL"> <br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Demo1.php
<?php
if(isset($_POST['submit']))
{
$FNAME=$_POST["FNAME"];
$LNAME=$_POST["LNAME"];
$EMAIL=$_POST["EMAIL"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentrecord";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "INSERT INTO STUD (FNAME,LNAME,EMAIL) VALUES ('$FNAME','$LNAME','$EMAIL')";