0% found this document useful (0 votes)
6 views14 pages

PHP_CH_05

MySQL is a widely-used relational database system that integrates well with PHP, offering advantages such as ease of use, security, and scalability. The document covers essential operations including connecting to the MySQL database, creating databases and tables, inserting, updating, selecting, and deleting records using SQL queries. It also provides examples of PHP code for interacting with MySQL databases, including form submissions for data entry.
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)
6 views14 pages

PHP_CH_05

MySQL is a widely-used relational database system that integrates well with PHP, offering advantages such as ease of use, security, and scalability. The document covers essential operations including connecting to the MySQL database, creating databases and tables, inserting, updating, selecting, and deleting records using SQL queries. It also provides examples of PHP code for interacting with MySQL databases, including form submissions for data entry.
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/ 14

PHP MySQL Introduction

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 |
+----+------------+-----------+----------------------------------+

Talking to MySQL Databases with SQL

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

Example : Connect to MySQL Database Server

Enter localhost in browser


Click on phpMyAdmin
First create myDB database in phpMyAdmin

<?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";
?>

Closing the MySQL Database Server Connection


The connection to the MySQL database server will be closed automatically as soon as the
execution of the script ends. However, if you want to close it earlier you can do this by
simply calling the PHP close() function.
Example
<?php
$conn = new mysqli("localhost", "root", "", "myDB");

if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}

// Print host information


echo "Connected successfully";
// Close connection
$conn ->close();
?>

Create a MySQL Database


The CREATE DATABASE statement is used to create a database in MySQL.
The following examples create a database named " studentrecord ":
Example
<?php
$servername = "localhost";
$username = "root";
$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 studentrecord";
if ($conn->query($sql) === TRUE)
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

Create a MySQL Table Using MySQLi


The CREATE TABLE statement is used to create a table in MySQL.

We will create a table named " STUDENT ", with columns: " roll ", "firstname", "lastname", "email"

CREATE TABLE STUDENT (


roll INT(6) AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50)
);

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);
}

// sql to create table


$sql = "CREATE TABLE STUDENT (
roll INT(6) AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50)
)";

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


{
echo "Table STUDENT created successfully";
}
else
{
echo "Error creating table: " . $conn->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);
}

// sql to create table


$sql = "INSERT INTO STUDENT (firstname, lastname, email)
VALUES ('Akshay','Somwanshi', 'Akshay@Somwanshi.com')";

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


{
echo "New record created successfully";
}
else
{
echo "Error ". $conn->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);
}

// sql to create table


$sql = "INSERT INTO STUDENT (firstname, lastname, email)
VALUES ('Amol','Somwanshi', 'Ampl@Somwanshi.com');";

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


VALUES ('abc','xyz', 'abc@xyz.com')";

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


{
echo "New record created successfully";
}
else
{
echo "Error ". $sql."<br>".$conn->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.

SELECT column_name(s) FROM table_name WHERE column_name operator value

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);
}

$sql = "SELECT roll, firstname, lastname FROM student WHERE lastname='somwanshi'";


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

$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);
}

$sql = "SELECT * FROM student WHERE lastname='somwanshi'";


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

$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";

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


{
echo "Record deleted successfully";
}
else
{
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Update Data In a MySQL Table
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

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

$sql = "UPDATE student SET lastname='Computer' WHERE roll=9";

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


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

$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')";

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


{
echo "New record created successfully";
}
else
{
echo "Error ". $conn->error;
}
$conn->close();
}
?>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy