13 – PHP MySQL Connection Informatics Department Parahyangan Catholic University.

Slides:



Advertisements
Similar presentations
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
Advertisements

Widhy Hayuhardhika NP, S.Kom. Overview of database structure Connecting to MySQL database Selecting the database to use Using the require_once statement.
Manipulating MySQL Databases with PHP. PHP and mySQL2 Objectives Connect to MySQL from PHP Learn how to handle MySQL errors Execute SQL statements with.
Objectives Connect to MySQL from PHP
MySQL and PHP By Trevor Adams.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 14: Advanced Topics: DBMS, SQL, and ASP.NET
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
CSCI 6962: Server-side Design and Programming
Session 5: Working with MySQL iNET Academy Open Source Web Development.
INTERNET APPLICATION DEVELOPMENT For More visit:
Create an online booking system (login/registration)
ASP.NET Programming with C# and SQL Server First Edition
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
MySQL + PHP.  Introduction Before you actually start building your database scripts, you must have a database to place information into and read it from.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
PHP meets MySQL.
Introduction to databases and SQL. What is a database?  A database is an organized way of holding together pieces of information  A database refers.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
Accessing MySQL with PHP IDIA 618 Fall 2014 Bridget M. Blodgett.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
Installing and Using MySQL and phpMyAdmin. Last Time... Installing Apache server Installing PHP Running basic PHP scripts on the server Not necessary.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Chapter 6 PHP Interacts with Mysql Database. Introduction In PHP, there is no consolidated interface. Instead, a set of library functions are provided.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
PHP Part 2.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
(Chapter 10 continued) Our examples feature MySQL as the database engine. It's open source and free. It's fully featured. And it's platform independent.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Design and Management CPTG /23/2015Chapter 12 of 38 Functions of a Database Store data Store data School: student records, class schedules,
Web-Based Database Programming with PHP. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn PHP Basics PHP functions –To.
CHAPTER 9 PHP AND MYSQL. A POSSIBLE SITE CONFIGURATION Application Folder index.php includes (folder)header.phpfooter.phpstyle.cssmodel (folder)mysqli_connect.php.
Dynamic web content HTTP and HTML: Berners-Lee’s Basics.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
2010/11 : [1]PHP with MySQLBuilding Web Applications using MySQL and PHP (W1) PHP with MySQL.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
CHAPTER 10 PHP MySQL Database
MySQL MySQL and PHP – interacting with a database.
8 th Semester, Batch 2009 Department Of Computer Science SSUET.
MYSQL AND MYSQL WORKBENCH MIS2502 Data Analytics.
Software-Projekt 2008 Seminarvortrag“Short tutorial of MySql“ Wei Chen Verena Honsel.
Radoslav Georgiev Telerik Corporation
COM621: Advanced Interactive Web Development Lecture 10 PHP and MySQL.
PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative.
Chapter 12 Introducing Databases. Objectives What a database is and which databases are typically used with ASP.NET pages What SQL is, how it looks, and.
ASP.NET Programming with C# and SQL Server First Edition
Chapter 5 Introduction to SQL.
Introduction to Dynamic Web Programming
Introduction to Web programming
Web Design and Development
mysql and mysql workbench
PHP Introduction.
ISC440: Web Programming 2 Server-side Scripting PHP 3
Web Systems Development (CSC-215)
Chapter 8 Working with Databases and MySQL
MySQL Web Application Connecting to a MySQL database
Web Programming Language
Intro to PHP.
Tutorial 6 PHP & MySQL Li Xu
MySQL Web Application Connecting to a MySQL database
Introduction to Web programming
Presentation transcript:

13 – PHP MySQL Connection Informatics Department Parahyangan Catholic University

 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'

 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)

 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.

 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

 Open localhost/phpmyadmin from your browser.

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

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

 Choose the privileges to be granted to the user

AUTO INCREMENT PRIMARY KEY

primary keyuniqueindex adding new column

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

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

 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.

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

 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.

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

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

DELETE MySql query: DELETE FROM webuser WHERE id=1

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.

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

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.

 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.

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

 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

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

$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

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

$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

 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)

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

 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

 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

 Other string functions that might be useful:  htmlspecialchars  htmlspecialchars_decode  trim  stripslashes  etc.  See:

 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.

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

 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.