PHP
Seiya Tanaka
Subject:
Internet and Web Development
Contents
Database
Posting content to database
Getting content from a database
File uploading
MySQL
MySQL is a database system used on the
web
MySQL is a database system that runs on a
server
MySQL uses standard SQL
MySQL is free to download and use
MySQL is developed, distributed, and
supported by Oracle Corporation
Using XAMPP
Start Apache and Mysql
Access to phpMyAdmin
(http://localhost/phpmyadmin/index.php)
This will bring you to the MySQL
setup page:
[default setting]
Username: root
Password: root
Create a MySQL
Database
Enter a name for the database, then click
on the Create button.
The name must be 64 characters or less
and composed of letters, numbers and
underscores.
Create a MySQL
Database
Ensure the database was successfully
created:
Create a table on the
database
To create a table, click on the tab
"Databases" and choose a database by
clicking on it:
Create a table on the
database
Then there will be a box titled "Create new
table in database", where you type the name
of the table and the number of columns and
press the button "Go":
Create a table on the
database
Then you can name the columns and set the
data type, etc., as in the SQL example
above.
Password setting
XAMPP default setting is no password
Enter the password from Security menu on
the admin window
Practice
Create a database and table as below
database name : lesson1
table name : login
table fields
Field Type Length Index
user VARCHAR 50 Primary
pass VARCHAR 100 -
Connect to MySQL
Before we can access data in the MySQL
database, we need to be able to connect to
the server.
Using PDO (PHP Data Objects) which is an
interface for accessing databases in PHP.
Web Server
DB(MySQL)
PHP PDO
Server
Connect to MySQL
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=lesson1",
$username, $password);
echo "Connected successfully";
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// close the connection
$conn = null;
?>
Explaining the code
Try and catch : This statement for Exception
handling. A connecting to DB code should be try {
in a "try" block. If it throws an exception, }
catch(PDOException $e) {
the "catch" block is executed
}
This line is connecting to Database using PDO
$conn = new PDO("mysql:host=$servername;dbname=lesson1", $username, $password);
When we finish to use a Database, we have
to close the connection
$conn = null;
Insert Data Into MySQL
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
Insert Data Into MySQL
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,…)
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=lesson1",
$username, $password);
echo "Connected successfully<br>";
// make a sql
$sql = "INSERT INTO login (user, pass)
VALUES ('user01', 'abcde')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// close the connection
$conn = null;
?>
Explaining the code
-> : This symbol mean:
A->B (code) = A's B (English)
exec() method is one of $conn's method
$conn->exec($sql);
exec() executes a SQL
exec() doesn't return value
Select Data from MySQL
The SELECT statement is used to get records
from one or more tables:
SELECT * FROM table_name
WHERE column1 = value1 AND column2 = value2;
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=lesson1",
$username, $password);
echo "Connected successfully<br>";
// make a sql
$sql = "SELECT * FROM login";
// use query() executes an SQL statement
foreach($conn->query($sql) as $row) {
echo $row['user'] . " ";
echo $row['pass'] . "<br>";
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// close the connection
$conn = null;
?>
Explaining the code
foreach() statement is a loop statement
The foreach loop works only on arrays, and is used to loop through
each key/value pair in an array
query() method is one of $conn method
query() returns value which is each key/value (Database field/value)
pair in an array
foreach($conn->query($sql) as $row) {
echo $row['user'] . " ";
echo $row['pass'] . "<br>";
}
Practice
Make a login form
login.html result.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=lesson1",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully<br>";
// make a sql
$sql = "SELECT * FROM login";
$stmt = $conn->query($sql);
// use query() executes an SQL statement
if($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['user'] . " is login.";
}else{
echo "no user or no password";
}
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// close the connection
$conn = null;
?>
Explaining the code
$stmt is return value of $conn->query($sql)
fetch(PDO::FETCH_ASSOC) returns a data from the result of sql
$stmt->fetch(PDO::FETCH_ASSOC)
File uploading
Step of file uploading
Configure The "php.ini" File
Create The HTML Form
Create The Upload File PHP Script
Configure
The "php.ini" File
First, ensure that PHP is configured to allow
file uploads.
In your "php.ini" file, search for the
file_uploads directive, and set it to On:
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users
to choose the image file they want to
upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/
form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Explaining the code
Make sure that the form uses method="post"
The form also needs the following attribute:
enctype="multipart/form-data". It specifies
which content-type to use when submitting
the form
The type="file" attribute of the <input> tag
shows the input field as a file-select control,
with a "Browse" button next to the input
control
Create The Upload File
PHP Script
The "upload.php" file contains the code for
uploading a file:
<?php
$target_file = "uploads/".$_FILES["fileToUpload"]["name"];
if(isset($_POST["submit"])) {
if (!move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "faild to copy";
exit;
}
echo "success to copy";
}
?>
Explaining the code
$_FILES["fileToUpload"]["name"] returns file
name
$_FILES["fileToUpload"]["tmp_name"] returns
temp file of uploaded file
move_uploaded_file(tempfile, filepath) method
copy the file to file path
Note: You will need to create a new directory called "uploads" in the
directory where "upload.php" file resides and change the directory auth to
"777". The uploaded files will be saved there.
Summary
Database
Posting content to database
Getting content from a database
File uploading