0% found this document useful (0 votes)
22 views

Lecture 1

This document provides an overview of PHP and MySQL. It discusses what MySQL is, how data is stored in tables with rows and columns. It also covers connecting to a MySQL database, creating tables, inserting, selecting, updating and deleting data from tables using PHP. Queries and WHERE clauses are also explained to retrieve specific records from tables.

Uploaded by

Štêv Ŵs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Lecture 1

This document provides an overview of PHP and MySQL. It discusses what MySQL is, how data is stored in tables with rows and columns. It also covers connecting to a MySQL database, creating tables, inserting, selecting, updating and deleting data from tables using PHP. Queries and WHERE clauses are also explained to retrieve specific records from tables.

Uploaded by

Štêv Ŵs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

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

Svendson Tove Borgvn 23 New york


Pettersen Kari Storgt 20 Paris

• 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:

SELECT FirstName FROM Persons


The query above selects all the data in the "LastName" column
from the "Persons" table, and will return a recordset like this
FirsttName
Hansen
Svendson
Pettersen
In this chapter we learn the following sections:
• Connecting to MySQL database
• Create MySQL Database Using PHP
• Delete MySQL Database Using PHP
• Insert Data To MySQL Database
• Retreving Data From MySQL Database
• Updating Data Into MySQL Database
• Deleting Data From MySQL Database
• Using PHP To Backup MySQL Database
PHP MySQL Connect to a Database
• Before you can access data in a database, you must
create a connection to the database.
• In PHP, this is done with the mysql_connect() function.
• Syntax
mysql_connect(servername,username,password,da
tabase);
Parameter Description

servername Optional. Specifies the server to connect to. Default value


is "localhost:3306"
username Optional. Specifies the username to log in with. Default
value is the name of the user that owns the server process
password Optional. Specifies the password to log in with. Default is ""
Example - Connect to a Database
• In the following example we store the connection in a
variable ($conn) for later use in the script. The "die"
part will be executed if the connection fails:

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

• Note: Notice the WHERE clause in the UPDATE syntax. The


WHERE clause specifies which record or records that should be
updated. If you omit the WHERE clause, all records will be
updated!
Example - Update Data in a Database Table
• The following example updates some data in the "Persons" table:

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

DELETE FROM table_name


WHERE some_column = some_value

• Note: Notice the WHERE clause in the DELETE syntax. The


WHERE clause specifies which record or records that should be
deleted. If you omit the WHERE clause, all records will be
deleted!
Example – Delete Data in a Database Table
• The following example deletes all the records in the "Persons"
table where LastName='Griffin':

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

You might also like