PHP Mysql

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 18

SCHOOL OF ENGINEERING

AND APPLIED SCIENCES

03 PHP & MYSQL

PhD. AMARSANAA Ganbold

DEPARTMENT OF INFORMATION AND COMPUTER SCIENCE


NUM, School of Engineering and Applied Sciences
amarsanaag@num.edu.mn

ICSI301 Web Programming


2017 Spring
OBJECTIVES
 MySQL
 SQL recap
 Database connection pool
 PHP Access to a database
 Insert, retrieve data
 SQL Injection

2
RECAP SQL
 SQL is a ANSI (American National Standards Institute) standard computer
language for accessing and manipulating databases.
 access a database
 execute queries, and retrieve data
 insert, delete and update records
 SQL works with database programs like MySQL, MS SQL Server, Oracle,
PostgreSQL, etc.
 DDL – Data Definition Language (CREATE TABEL, DROP VIEW…)
 DML – Data Manipulation Language (SELECT,INSERT,UPDATE,DELETE)
 Relational database
 contains one or more tables, each table contain records
 RDBMS (Relational Database Management System)
 Standalone. e.g., MySQLi, MS Access etc.
 Server: e.g., MySQL, Oracle etc.
o requires credentials: domain, username, password, database

3
ACCESSING MYSQL
 three main ways:
 using a command line
 via an interface such as web based phpMyAdmin and GUI MySQL Workbench etc.
 through a programming language like PHP

4
ACCESSING MYSQL [2]
 using Linux

5
DATABASE CONNECTION
 a connection pool is a cache of database connections maintained so that
the connections can be reused when future requests to the database are
required.
Command-Line --max_connections=#
Format
System Name max_connections
Variable
Variable Scope Global
Dynamic Yes
Variable
Permitted Type integer
Values
Default 151
Min Value 1
Max Value 100000

 In MySQL 5.5
mysql> SET GLOBAL max_connections =
5000;
Query OK, 0 rows affected (0.00 sec)

6
QUERYING A MYSQL DATABASE WITH PHP
 The process of using MySQL with PHP is:
1. Connect to MySQL.
2. Select the database to use.
3. Build a query string.
4. Perform the query.
5. Retrieve the results and output them to a web page.
6. Repeat Steps 3 to 5 until all desired data has been retrieved.
7. Disconnect from MySQL.

7
PHP ACCESS TO A DATABASE
1. Connect to the database server and login
$db = mysqli_connect("host", "username", "password");
returns a database handle — a representation of PHP’s connection to the
database.
2. Choose the database
mysqli_select_db("database_name",$db);
to select and open the database to be queried
3. Send queries to the server to add, delete, modify and retrieve data
mysqli_query("query" ,$db);
specifying the query string and the database to query
4. Close the connection
mysqli_close();

NOTE: mysql_query was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
8
INSERT DATA
<html>
<head><title>Putting Data in the DB</title></head>
<body>
<?php
/*insert students into DB*/
if(isset($_POST["submit"])) {
$db = mysqli_connect("mysql", "martin");
mysqli_select_db("martin");
$date=date("Y-m-d");/*Get the current date in the right SQL format */
$sql="INSERT INTO students VALUES(NULL,'" . $_POST["f_name"] . "','" .
$_POST["l_name"] . "'," . $_POST["student_id"] . ",'" . $_POST["email"] .
"','" . $date . "'," . $_POST["gr"] . ")"; /* construct the query */
mysqli_query($sql);
mysqli_close();

echo"<h3>Thank you. The data has been entered.</h3> \n";


echo'<p><a href="data_in.php">Back to registration</a></p>' . "\n";
echo'<p><a href="data_out.php">View the student lists</a></p>' ."\n";

}
else {
?>

9
INSERT DATA [2]
<h3>Enter your items into the database</h3>
<form action="data_in.php" method="POST">
First Name: <input type="text" name="f_name" /> <br/>
Last Name: <input type="text" name="l_name" /> <br/>
ID: <input type="text" name="student_id" /> <br/>
email: <input type="text" name="email" /> <br/>
Group: <select name="gr">
<option value ="1">1</option>
<option value ="2">2</option>
<option value ="3">3</option>
<option value ="4">4</option>
</select><br/><br/>
<input type="submit" name="submit" /> <input type="reset" />
</form>

<?php
}
?>

</body>
</html>

10
RETRIEVE DATA
 Send an SQL query to the server to select data from the database into an
array
$result=mysqli_query("query");
 Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN
queries mysqli_query() will return a mysqli_result object. For other successful
queries it will return TRUE.
 Either, look into a row and a fieldname
$num=$result->num_rows;
$variable=mysqli_result($result,$i,"fieldname");
 Or, fetch rows one by one
$row=$result->fetch_array;
$row[key]

11
RETRIEVE DATA: DATA_OUT.PHP
<html>
<head><title>Getting Data out of the DB</title></head>
<body>
<h1> Student Database </h1>
<p> Order the full list of students by
<a href="data_out.php?order=date">date</a>,
<href="data_out.php?order=student_id">id</a>, or
by <a href="data_out.php?order=l_name">surname</a>.</p>

<p><form action="data_out.php" method="POST">


Or only see the list of students in group
<select name="gr">
<option value ="1">1</option>
<option value ="2">2</option>
<option value ="3">3</option>
<option value ="4">4</option>
</select><br/>
<input type="submit" name="submit" />
</form></p>

12
RETRIEVE DATA: DATA_OUT.PHP
<?php
/*get students from the DB */
$db = mysqli_connect("mysql","martin");
mysqli_select_db("martin", $db);

switch($_GET["order"]){
case 'date': $sql = "SELECT * FROM students ORDER BY date"; break;
case 'student_id': $sql = "SELECT * FROM students ORDER BY student_id";
break;
case 'l_name': $sql = "SELECT * FROM students ORDER BY l_name"; break;

default: $sql = "SELECT * FROM students";


}
if(isset($_POST["submit"])){
$sql = "SELECT * FROM students WHERE gr=" . $_POST["gr"];
}

$result=mysqli_query($sql);
while($row=mysqli_fetch_array($result)){
echo "<h4> Name: " . $row["l_name"] . ', ' . $row["f_name"] . "</h4> \n";
echo "<h5> ID: " . $row["student_id"] . "<br/> Email: " . $row["email"] .
"<br/> Group: " . $row["gr"] . "<br/> Posted: " . $row["date"] . "</h5> \n";
}
mysqli_close();
?>
</body>
</html> view the output page 13
MORE QUERIES WITH PHP
 Can create a table
 Can delete rows and columns
 Can make updates
 Can make queries to several tables
 Can get connected to several databases
 Remember the connection concept

14
CREATING A LOGIN FILE
 multiple program files that will require access to MySQL and will thus need
the login and password details
 create a single file to store these and then include that file wherever it’s needed

<?php // login.php
$db_hostname = 'localhost';
$db_database = 'publications';
$db_username = 'username';
$db_password = 'password';
?>

<?php // news.php
include_once("login.php");
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
?>

15
SQL INJECTION
 is a technique where malicious users can inject SQL commands into an
SQL statement, via web page input.
 For example, from resetting a password ... to gaining more privileges (any
database server)
<?php
$uid = $_POST["uid"]; // beware, no input validation!
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
$result = mysqli_query($conn, $query);
?>

<?php
// $uid: ' or uid like '%admin%
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';";

// $pwd: hehehe', trusted=100, admin='yes


$query = "UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE
...;";
?>

Avoidance Techniques
 consider verifying data
 settype($offset, 'integer');
 sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
$offset);

 string escape function


 mysql_real_escape_string(), sqlite_escape_string() etc. 16
Any questions?

No?

17
QUESTIONS
1. What tag is used to cause PHP to start interpreting program code? And what
is the short form of the tag?
2. What are the two types of comment tags?
3. Which character must be placed at the end of every PHP statement?
4. Which symbol is used to preface all PHP variables?
5. What can a variable store?
6. What is the difference between $variable = 1 and $variable == 1?
7. Why do you suppose an underscore is allowed in variable names (e.g.,
$current_user) whereas hyphens are not (e.g., $current-user)?
8. Are variable names case-sensitive?

18

You might also like