Presentation is loading. Please wait.

Presentation is loading. Please wait.

13 – PHP MySQL Connection Informatics Department Parahyangan Catholic University.

Similar presentations


Presentation on theme: "13 – PHP MySQL Connection Informatics Department Parahyangan Catholic University."— Presentation transcript:

1 13 – PHP MySQL Connection Informatics Department Parahyangan Catholic University

2  The SQL in MySQL stands for Structured Query Language.  This language is loosely based on English and is also used on other databases, such as Oracle and Microsoft SQL Server.  It is designed to allow simple requests from a database via commands such as: SELECT title FROM publications WHERE author='Charles Dickens'

3  MySQL is an open-source relational database management system (RDBMS)  In July 2013, it was the world's second most widely used RDBMS, and the most widely used open- source client–server model RDBMS  MySQL is a popular choice of database for use in web applications, and is a central component of the widely used LAMP(Linux Apache MySQL PHP/Perl/Python) open source web application software stack (and other "AMP" stacks)

4  On all platforms except Windows, MySQL ships with no GUI tools to administer MySQL databases or manage data contained within the databases.  Users may use the included command line tools, or install MySQL Workbench via a separate download.  Many third party GUI tools are also available.

5  is a free software tool written in PHP, intended to handle the administration of MySQL over the Web.  supports a wide range of operations on MySQL and MariaDB.  Frequently used operations can be performed via the user interface, while you still have the ability to directly execute any SQL statement.  Usually included in the XAMPP installer

6  Open localhost/phpmyadmin from your browser.

7

8  From phpMyAdmin’s home:  Click “Add a new User” link.  Fill this form:

9  On “priviledges” page:  Choose the database here:

10  Choose the privileges to be granted to the user

11

12 AUTO INCREMENT PRIMARY KEY

13 primary keyuniqueindex adding new column

14 for security, never store password in raw text MySql query: INSERT INTO `webuser` (`id`,`username`,`password`,`fullname`) VALUES (1, 'alice88', MD5('AbCdEf'), 'Alice Smith')

15 MySql query: SELECT * FROM `webuser` LIMIT 0,30

16  The SELECT command is used to extract data from a table.  The basic syntax is: SELECT something FROM tablename;  The something can be an * (asterisk), to indicate “every column”, or we can choose to select only certain columns by specifying the columns’ name separated by a coma.

17 MySql query: SELECT username, fullname FROM webuser MySql query: SELECT COUNT(*) FROM webuser

18  The WHERE keyword enables you to narrow down queries by returning only those where a certain expression is true.  The LIKE and NOT LIKE keyword is used for pattern matching. “_” matches to a single character, and “%” matches an arbitrary number of character. In MySQL, pattern is case-insensitive by default.

19 MySql query: SELECT * FROM webuser WHERE fullname LIKE '%smith%' MySql query: SELECT * FROM webuser WHERE username='alice88'

20 MySql query: SELECT * FROM webuser WHERE fullname NOT LIKE '%a%' MySql query: SELECT * FROM webuser WHERE id >=5 AND id<9

21 DELETE MySql query: DELETE FROM webuser WHERE id=1

22 Sometimes it is necessary to keep the old data, for example when we want to deactivate some user, but want to keep all his/her activities on our website. In such case, we can use a boolean field to mark which record is already deleted. This approach also allows us to restore the deleted account later on.

23  This construct allows you to update the contents of a field Example: UPDATE webuser SET password=MD5('asdfgh') WHERE username='bob123'

24 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 through 5 until all desired data has been retrieved. 7. Disconnect from MySQL.

25  A connector is a piece of software that allows your application to connect to the MySQL database server.  The PHP code consists of a core, with optional extensions to the core functionality.  PHP's MySQL-related extensions, such as the mysqli (object oriented) extension, and the mysql (procedural) extension, are implemented using the PHP extension framework.  The mysqli extension allows you to access the functionality provided by MySQL 4.1 and above.

26  Creates a new mysqli object with 4 parameters:  server name/ IP address  MySQL username  MySQL password  Database name

27  Example: <?php $mysqli = new mysqli("localhost", "pbw", "pbw39", "pbw"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (". $mysqli->connect_errno. ") ". $mysqli->connect_error; } else{ // DB Querying here… echo "Successfully connected to database"; } ?> usernamepassworddatabase nameserver

28  Statements can be executed with the mysqli_query() function.  The mysqli_query() function combines the executing statement with a buffered fetch of its result set, if any, in one call. $sql = "INSERT INTO webuser (username, password, fullname) VALUES ('kenny', MD5('kenny'), 'Kenny Rake')"; $result = $mysqli->query($sql); if($result) echo "Data successfully added"; Example:

29 $username = "alice88"; $password = md5("AbCdEf"); $sql = "SELECT * FROM webuser WHERE username='$username' AND isdeleted = 0"; $result = $mysqli->query($sql); if($result && $result->num_rows > 0){ $row = $result->fetch_array(); if($row['password'] == $password) echo "Login successful"; else echo "Error: Wrong password"; } else{ echo "Error: Username $username does not exist"; } can be taken from $_GET, $_POST, etc. same as with echo, variable is automatically replaced with its content when the string uses “” checks whetrher the query returned some rows fetch one record

30 $sql = "SELECT username, fullname FROM webuser WHERE isdeleted=0"; $result = $mysqli->query($sql); if($result && $result->num_rows > 0){ echo " "; echo " Username "; echo " Full Name "; while($row = $result->fetch_array()){ printf(" %s %s ", $row['username'], $row['fullname']); } echo " "; } Example:

31 $username = "bob123"; $oldpass = md5("asdfgh"); $newpass = md5("ASDFGH"); $sql = "SELECT * FROM webuser WHERE username='$username' ". "AND password='$oldpass'"; $result = $mysqli->query($sql); if($result && $result->num_rows > 0){ $sql = "UPDATE webuser SET password='$newpass' ". "WHERE username='$username'"; $result = $mysqli->query($sql); if($result) echo "Password successfully updated"; else echo "Failed to update password"; } can be taken from $_GET, $_POST, etc. important to check whether the old password is correct. $result->num_rows > 0 makes sure that the user exist and the old password is correct

32  Sometimes we have codes that is used on more than one page (Ex: connecting to database).  The include command includes a file of PHP code to another. (similar to Java’s import)

33 <?php global $mysqli; $mysqli = new mysqli("localhost", "pbw", "pbw39", "pbw"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (". $mysqli->connect_errno. ") ". $mysqli->connect_error; } ?> connection.php <?php include 'connection.php'; //other codes… ?> otherfile.php

34  Data to be inserted into database can be taken from $_GET, $_POST, or other sources.  They may contains single or double quote character (' or "). For example, a person’s name is O’reilly  If we try to instert it to a database, the SQL query might looks like this: $sql = "INSERT INTO webuser (username, password, fullname) VALUES ". "('oreilly', MD5('abc123'), 'O'reilly')"; This would cause error, because there’s and extra single quote without matching closing quote

35  The real_escape_string() function of MySQLi escapes special characters in a string for use in an SQL statement  Example: $name = "O'reilly"; $escapedname = $mysqli->real_escape_string($name); echo $escapedname;//writes: O\'reilly

36  Other string functions that might be useful:  htmlspecialchars  htmlspecialchars_decode  trim  stripslashes  etc.  See: http://php.net/manual/en/ref.strings.phphttp://php.net/manual/en/ref.strings.php

37  The htmlspecialchars() function convert special characters to HTML entities  Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings.  Example:  '&' (ampersand) becomes '&'  '<' (less than) becomes '<'  etc.

38  Example: $text = " means line break"; $specialtext = htmlspecialchars($text); echo "Before: ".$text." "; echo "After: ".$specialtext." ";

39  The htmlspecialchars_decode() function convert special HTML entities back to characters  This function is the opposite of htmlspecialchars(). It converts special HTML entities back to characters.


Download ppt "13 – PHP MySQL Connection Informatics Department Parahyangan Catholic University."

Similar presentations


Ads by Google