chapter 10 php mysql database

31
CHAPTER 10 PHP MySQL Database อ.อออออ อออออออออ ออออออออออออออออออออออออออ อออออออ ออออออออออออออออ 1

Upload: lizbeth-francis

Post on 06-Jan-2018

254 views

Category:

Documents


3 download

DESCRIPTION

Content PHP MySQL Database PHP Connect to MySQL PHP Create a MySQL Database PHP Create MySQL Tables PHP Insert Data Into MySQL PHP Get ID of Last Inserted Record PHP Insert Multiple Records Into MySQL PHP Prepared Statements

TRANSCRIPT

Page 1: CHAPTER 10 PHP MySQL Database

CHAPTER 10PHP MySQL Database

อ. ยนืยง กันทะเนตรคณะเทคโนโลยสีารสนเทศและการสื่อสาร

มหาวทิยาลัยพะเยา

1

Page 2: CHAPTER 10 PHP MySQL Database

Content

• PHP MySQL Database• PHP Connect to MySQL• PHP Create a MySQL Database• PHP Create MySQL Tables• PHP Insert Data Into MySQL• PHP Get ID of Last Inserted Record• PHP Insert Multiple Records Into MySQL• PHP Prepared Statements

2

Page 3: CHAPTER 10 PHP MySQL Database

Content

• PHP Select Data From MySQL• PHP Delete Data From MySQL• PHP Update Data in MySQL• PHP Limit Data Selections From MySQL

3

Page 4: CHAPTER 10 PHP MySQL Database

PHP MySQL Database

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• MySQL compiles on a number of platforms• MySQL is free to download and use• MySQL is developed, distributed, and supported by Oracle Corporation• MySQL is named after co-founder Monty Widenius's daughter: My

4

Page 5: CHAPTER 10 PHP MySQL Database

PHP MySQL Database

Database QueriesA query is a question or a request.We can query a database for specific information and have a recordset returned.

SELECT LastName FROM Employees

5

Download MySQL DatabaseIf you don't have a PHP server with a MySQL Database, you can download it for free here: http://www.mysql.com

Page 6: CHAPTER 10 PHP MySQL Database

PHP Connect to MySQL

PHP 5 and later can work with a MySQL database using:• MySQLi extension (the "i" stands for improved)• PDO (PHP Data Objects)

6

Should I Use MySQLi or PDO?Both MySQLi and PDO have their advantages:PDO will work on 12 different database systems, where as MySQLi will only work with MySQL databases.

Page 7: CHAPTER 10 PHP MySQL Database

PHP Connect to MySQL (cont.)MySQL Examples in Both MySQLi and PDO SyntaxIn this, and in the following chapters we demonstrate three ways of working with PHP and MySQL:• MySQLi (object-oriented)• MySQLi (procedural)• PDO

7

MySQLi InstallationFor Linux and Windows: The MySQLi extension is automatically installed in most cases, when php5 mysql package is installed.For installation details, go to: http://php.net/manual/en/mysqli.installation.php* This course uses MySQLi (procedural)

Page 8: CHAPTER 10 PHP MySQL Database

PHP Connect to MySQL (cont.)Example (MySQLi Procedural)<?php$servername = "localhost";$username = "username";$password = "password";

// Create connection$conn = mysqli_connect($servername, $username, $password);

// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}echo "Connected successfully";?>

8

Page 9: CHAPTER 10 PHP MySQL Database

PHP Connect to MySQL (cont.)Close the ConnectionThe connection will be closed automatically when the script ends. To close the connection before, use the following:

Example (MySQLi Procedural)

mysqli_close($conn);

9

Page 10: CHAPTER 10 PHP MySQL Database

PHP Create a MySQL DatabaseCreate a MySQL Database Using MySQLiThe CREATE DATABASE statement is used to create a database in MySQL.The following examples create a database named "myDB":

<?php$servername = "localhost";$username = "username";$password = "password";

// Create connection$conn = mysqli_connect($servername, $username, $password);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());} 10

Page 11: CHAPTER 10 PHP MySQL Database

PHP Create a MySQL DatabaseCreate a MySQL Database Using MySQLi (cont.)

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

11

Page 12: CHAPTER 10 PHP MySQL Database

PHP Create MySQL TablesThe CREATE TABLE statement is used to create a table in MySQL.

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

)

12

Page 13: CHAPTER 10 PHP MySQL Database

PHP Create MySQL Tables (cont.)Example (MySQLi Procedural)<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB";

// Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());} 13

Page 14: CHAPTER 10 PHP MySQL Database

PHP Create MySQL Tables (cont.)Example (MySQLi Procedural) (cont.)

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

)";

14

Page 15: CHAPTER 10 PHP MySQL Database

PHP Create MySQL Tables (cont.)Example (MySQLi Procedural) (cont.)

if (mysqli_query($conn, $sql)) { echo "Table MyGuests created successfully";} else { echo "Error creating table: " . mysqli_error($conn);}

mysqli_close($conn);?>

15

Page 16: CHAPTER 10 PHP MySQL Database

PHP Insert Data Into MySQLThe 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 "id" column) or TIMESTAMP (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value.

16

Page 17: CHAPTER 10 PHP MySQL Database

PHP Insert Data Into MySQLExample (MySQLi Procedural)<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB";

// Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());} 17

Page 18: CHAPTER 10 PHP MySQL Database

PHP Insert Data Into MySQLExample (MySQLi Procedural)

$sql = "INSERT INTO MyGuests (firstname, lastname, email)VALUES ('John', 'Doe', '[email protected]')";

if (mysqli_query($conn, $sql)) { echo "New record created successfully";} else { echo "Error: " . $sql . "<br>" . mysqli_error($conn);}

mysqli_close($conn);?>

18

Page 19: CHAPTER 10 PHP MySQL Database

PHP Get ID of Last Inserted RecordExample (MySQLi Procedural)

…if (mysqli_query($conn, $sql)) { $last_id = mysqli_insert_id($conn); echo “Successfully. Last inserted ID is: " . $last_id;} else { echo "Error: " . $sql. "<br>" . mysqli_error($conn);}…

19

Page 20: CHAPTER 10 PHP MySQL Database

PHP Insert Multiple Records Into MySQLInsert Multiple Records Into MySQL Using MySQLi…$sql = "INSERT INTO MyGuests (firstname, lastname, email)VALUES ('John', 'Doe', '[email protected]');";$sql .= "INSERT INTO MyGuests (firstname, lastname, email)VALUES ('Mary', 'Moe', '[email protected]');";$sql .= "INSERT INTO MyGuests (firstname, lastname, email)VALUES ('Julie', 'Dooley', '[email protected]')";

if (mysqli_multi_query($conn, $sql)) { echo "New records created successfully";} else { echo "Error: " . $sql . "<br>" . mysqli_error($conn);}… 20

Page 21: CHAPTER 10 PHP MySQL Database

PHP Prepared StatementsPrepared Statements and Bound Parameters• Prepare: An SQL statement template is created and sent to the

database. Certain values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)

• The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it

• Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values

21

Page 22: CHAPTER 10 PHP MySQL Database

PHP Prepared Statements (cont.)Compared to executing SQL statements directly, prepared statements have two main advantages:• Prepared statements reduces parsing time as the preparation

on the query is done only once (although the statement is executed multiple times)

• Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole query

• Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.

22

Page 23: CHAPTER 10 PHP MySQL Database

PHP Prepared Statements (cont.)Example (MySQLi with Prepared Statements)<?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB";

// Create connection$conn = new mysqli($servername, $username, $password, $dbname);

// Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);} 23

Page 24: CHAPTER 10 PHP MySQL Database

PHP Prepared Statements (cont.)Example (MySQLi with Prepared Statements) (cont.)

// prepare and bind$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute$firstname = "John";$lastname = "Doe";$email = "[email protected]";$stmt->execute();

24

Page 25: CHAPTER 10 PHP MySQL Database

PHP Prepared Statements (cont.)Example (MySQLi with Prepared Statements) (cont.)$firstname = "Mary";$lastname = "Moe";$email = "[email protected]";$stmt->execute();

$firstname = "Julie";$lastname = "Dooley";$email = "[email protected]";$stmt->execute();

echo "New records created successfully";

$stmt->close();$conn->close();?>

25

Page 26: CHAPTER 10 PHP MySQL Database

PHP Select Data From MySQL

Select Data From a MySQL DatabaseThe SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name

or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name

26

Page 27: CHAPTER 10 PHP MySQL Database

PHP Select Data From MySQL (cont.)…$sql = "SELECT id, firstname, lastname FROM MyGuests";$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; }} else { echo "0 results";}…

27

Page 28: CHAPTER 10 PHP MySQL Database

PHP Delete Data From MySQLDelete Data From a MySQL Table Using MySQLi

DELETE FROM table_nameWHERE some_column = some_value

Example (MySQLi Procedural)…$sql = "DELETE FROM MyGuests WHERE id=3";

if (mysqli_query($conn, $sql)) { echo "Record deleted successfully";} else { echo "Error deleting record: " . mysqli_error($conn);}… 28

Page 29: CHAPTER 10 PHP MySQL Database

PHP Update Data in MySQLUpdate Data In a MySQL Table Using MySQLi

UPDATE table_nameSET column1=value, column2=value2,...WHERE some_column=some_value

Example (MySQLi Procedural)…$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if (mysqli_query($conn, $sql)) { echo "Record updated successfully";} else { echo "Error updating record: " . mysqli_error($conn);}… 29

Page 30: CHAPTER 10 PHP MySQL Database

PHP Limit Data Selections From MySQLLimit Data Selections From a MySQL DatabaseMySQL provides a LIMIT clause that is used to specify the number of records to return.

$sql = "SELECT * FROM Orders LIMIT 30";

What if we want to select records 16 - 25 (inclusive)?$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";or$sql = "SELECT * FROM Orders LIMIT 15, 10";

30

Page 31: CHAPTER 10 PHP MySQL Database

31

THE END