Lecture 1
Lecture 1
PHP MySql
PHP MySQL Introduction
What is MySQL?
• MySQL is a database.
• The data in MySQL is stored in database objects called
tables.
• A table is a collection of related data entries and it
consists of columns and rows.
• Databases are useful when storing information
categorically.
• i.e - A company may have a database with the following
tables: "Employees", "Products", "Customers" and
"Orders".
…cont
Database Tables
• A database most often contains one or more tables. Each
table is identified by a name (e.g. "Customers" or "Orders").
Tables contain records (rows) with data.
• Below is an example of a table called "Persons":
FirstName LastName Address City
Hansen Ola Timoteivn 10 London
• The table above contains three records (one for each person) and four
columns (LastName, FirstName, Address, and City).
..cont
Queries
• A query is a question or a request.
• With MySQL, we can query a database for specific
information and have a recordset returned.
• Look at the following query:
<?php
$con =
mysql_connect("localhost",”root”,””,”user_db”);
if (!$con)
{
die('Could not connect: '.mysqli_error());
}
?>
Closing a Database Connection
• The connection will be closed automatically when the
script ends. To close the connection before, use the
mysqli_close() function:
<?php
$con = mysql_connect("localhost",”root”,””,”user_db);
if (!$con)
{
die('Could not connect: '.mysqli_error());
}
//some code
mysqli_close($conn);
?>
Creating a Table
<?php
$sql = "CREATE TABLE IF NOT EXISTS Person
(FirstName varchar(15),LastName varchar(15),Age int)";
$create = mysqli_query($con,$sql);
if (!$create) {
die("Unable to create table: " . @mysqli_error());
}
else{
echo "<h1>New Table Created Successfully</h1>";
}?>
?>
Example - Create a table
• The following example creates a table called “Person”:
<?php
$con = mysqli_connect($host, $user, $pass, $db);
if (!$con) {
die("Unable to connect to MySQL: " . @mysqli_error()); }
else{
echo "<h1>Database Connected Successfully</h1>"; }
//Creating Table
$sql = "CREATE TABLE IF NOT EXISTS Person
(FirstName varchar(15),LastName varchar(15),Age int)";
$create = mysqli_query($con,$sql);
if (!$create) {
die("Unable to create table: " . @mysqli_error());
}
else{
echo "<h1>New Table Created Successfully</h1>";
Example - Insert Data Into a Database Table
• In the previous chapter we created a table named "Persons",
with three columns; "Firstname", "Lastname" and "Age".
• We will use the same table in this example. The following
example adds a new records to the "Persons" table:
<?php
$con = mysqli_connect($host, $user, $pass, $db);
//Inserting data into table
$sql = "INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin',35)";
$insert = mysqli_query($con,$sql);
if (!$insert) {
die("Unable to insert data into table: " . @mysqli_error());
}
else{
echo "<h1>New Data inserted Successfully</h1>";
}?>
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 "Persons" table.
• Here is the HTML form:
<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>
• 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 "Persons" table.
• Here is the "insert.php" page:
<?php
include("connect_db.php");
$fname = $_POST["firstname"];
$lname = $_POST["lastname"];
$age = $_POST["age"];
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES('$fname','$lname','$age');";
$insert = mysqli_query($con,$sql);
if (!$insert) { die('Error: ' . @mysqli_error()); }
mysqli_close($con);
}
header("location: lab2.php")
?>
Example - Selecting Table
• The following example selects all the data stored in the
"Persons" table (The * character selects all the data in the table):
<?php
include("connect_db.php");
$sql = "SELECT * FROM Persons";
$result = mysqli_query($con, $sql);
//Getting Results from MySQL
while($row = mysqli_fetch_assoc($result)){
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysqli_close($con);
?>
Example - Selecting (Where Clause)
• The WHERE clause is used to extract only those records that fulfill a
specified criterion.
• The following example selects all rows from the "Persons" table where
"FirstName='Peter'":
<?php
include("connect_db.php");
$sql = "SELECT * FROM Persons WHERE FirstName='Peter' ";
$result = mysqli_query($con, $sql);
//Getting Results from MySQL
while($row = mysqli_fetch_assoc($result)){
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysqli_close($con);
?>
Example - Selecting (ORDER BY Clause)
• The ORDER BY keyword is used to sort the data in a recordset.
• The ORDER BY keyword sort the records in ascending order by default.
• If you want to sort the records in a descending order, you can use the DESC
keyword.
<?php
include("connect_db.php");
$sql = "SELECT * FROM Persons ORDER BY age ASC";
$result = mysqli_query($con, $sql);
//Getting Results from MySQL
while($row = mysqli_fetch_assoc($result)){
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysqli_close($con);
?>
..cont
Order by Two Columns
• It is also possible to order by more than one column.
When ordering by more than one column, the second
column is only used if the values in the first column are
equal:
Update Data in a Database Table
• The UPDATE statement is used to update existing records in a
table.
• Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
<?php
include("connect_db.php");
$sql="UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin';";
$update = mysqli_query($con,$sql);
if (!$update) {
die('Error: ' . @mysqli_error());
}
mysqli_close($con);
}
?>
Delete Data in a Database Table
• The DELETE FROM statement is used to delete records from a
database table.
• Syntax
<?php
include("connect_db.php");
$sql="DELETE FROM Persons WHERE LastName='Griffin';";
$delete = mysqli_query($con,$sql);
if (!$delete) {
die('Error: ' . @mysqli_error());
}
mysqli_close($con);
}
?>