PHP MySQL Database
• With PHP, you can connect to and manipulate databases.
• MySQL is the most popular database system used with PHP.
What is MySQL?
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.
1
• The data in a MySQL database are stored in tables.
• A table is a collection of related data, and it consists of columns and
rows.
• Databases are useful for storing information categorically.
• A company may have a database with the following tables:
• Employees
• Products
• Customers
• Orders
PHP + MySQL Database System
o PHP combined with MySQL are cross-platform (you can develop
2
in Windows and serve on a Unix platform)
Database Queries
• A query is a question or a request.
• We can query a database for specific information and have a recordset
returned.
• Look at the following query (using standard SQL):
• The query above selects all the data in the "LastName" column from
the "Employees" table.
3
PHP Connect to MySQL
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able
to connect to the server:
• Example (MySQLi Object-Oriented)
<?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";
?> 4
• Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
5
Close the Connection
• The connection will be closed automatically when the script ends.
• To close the connection before, use the following:
MySQLi Object-Oriented:
$conn->close();
MySQLi Procedural:
mysqli_close($conn);
6
PHP Create a MySQL Database
• A database consists of one or more tables.
• You will need special CREATE privileges to create or to delete a
MySQL database.
• The CREATE DATABASE statement is used to create a database in
MySQL.
o Note: When you create a new database, you must only specify the
first three arguments to the mysqli object (servername, username and
password).
• The following examples create a database named "myDB":
• Example (MySQLi Object-oriented)
7
<?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;
}
8
$conn->close(); ?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn); ?> 9
PHP MySQL Create Table
• A database table has its own unique name and consists of columns and
rows.
• 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 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
)
10
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);
}
11
// sql to create table
$sql = "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
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
12
PHP MySQL 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,...) 13
Insert Data From a Form Into a Database
• Now we will create an HTML form that can be used to add new
records to the "Person" table.
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" /><input type="submit" />
</form>
</body>
</html 14
• When a user clicks the submit button in the HTML form in the
example above, the form data is sent to "insert.php".
• The "insert.php" file connects to a database, and retrieves the values
from the form with the PHP $_POST variables.
• Then, the mysql_query() function executes the INSERT INTO
statement, and a new record will be added to the database table.
Below is the code in the "insert.php" page:
15
<?php
$con = mysql_connect("localhost",“root","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO person (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
16
PHP MySQL Select
• The SELECT statement is used to select data from a database.
Select Data From a Database Table
Syntax
SELECT column_name(s) FROM table_name
Note: SQL statements are not case sensitive. SELECT is the same as
select.
• To get PHP to execute the statement above we must use the
mysql_query() function.
• This function is used to send a query or command to a MySQL
connection. 17
Reading Assignment
Retrieve data from a database.
Modify/updating existing data.
Remove existing data.
Database security using server side scripting.
Encryption in PHP.
SQL injection.
18
h !
u c
M
S o
o u
Y
n k
h a
T 19