Unit 2 MY SQL DATABASE PROGRAMMING

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
© 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.
Slide 8-1 CHAPTER 8 Using Databases with PHP Scripts: Using MySQL Database with PHP.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
INTERNET APPLICATION DEVELOPMENT For More visit:
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
PHP – MySQL Extensions. Table used in most examples CREATE TABLE product ( rowID INT NOT NULL AUTO_INCREMENT, productid VARCHAR(8) NOT NULL, name VARCHAR(25)
INTERNET APPLICATION DEVELOPMENT PRACTICAL ON CONNECTING TO MYSQL.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
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.
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.
School of Computing and Information Systems CS 371 Web Application Programming PHP – Forms, Cookies, Sessions and Database.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL.
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.
Lecture 10 – MYSQL and PHP (Part 2)
Website Development with PHP and MySQL Saving Data.
MySQL Database Connection
Web-Based Database Programming with PHP. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn PHP Basics PHP functions –To.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
PHP: MySQL. 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.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
>> Introduction to MySQL. Introduction Structured Query Language (SQL) – Standard Database Language – Manage Data in a DBMS (Database Management System)
CHAPTER 10 PHP MySQL Database
CSC 2720 Building Web Applications Accessing MySQL from PHP.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
COSC 2328 – Web Programming.  PHP is a server scripting language  It’s widely-used and free  It’s an alternative to Microsoft’s ASP and Ruby  PHP.
MySQL Tutorial. Databases A database is a container that groups together a series of tables within a single structure Each database can contain 1 or more.
1 PHP and MySQL Web Development When you install PHP, you can select from a number of extensions. The MySQL support in PHP consists of a number of functions.
 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.
PHP & MY SQL Instructor: Monireh H. Sayadnavard 1.
Web Systems & Technologies
Tried my best to simplify it for you!
PHP (Session 2) INFO 257 Supplement.
PHP: MySQL Lecture 14 Kanida Sinmai
Remote hosts and web servers
Chapter 5 Introduction to SQL.
CIIT-Human Computer Interaction-CSC456-Fall-2015-Mr
Open Source Server Side Scripting Permissions & Users
PHP Functions Besides the built-in PHP functions, we can create our own functions. A function is a block of statements that can be used repeatedly in.
Session 4 PHP & MySQL.
Web Design and Development
Server-Side Application and Data Management IT IS 3105 (FALL 2009)
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Introduction to Web programming
Objectives Connect to MySQL from PHP Learn how to handle MySQL errors
PHP and MySQL.
ISC440: Web Programming 2 Server-side Scripting PHP 3
DATABASE MANAGEMENT SYSTEM
Dr. John P. Abraham Professor UTRGV eCommerce CSCI 6314
Erasmus Exchange in Ionian University
MySQL Web Application Connecting to a MySQL database
Software Engineering for Internet Applications
PHP: Database connection
Tutorial 6 PHP & MySQL Li Xu
Web Programming– UFCFB Lecture
MySQL Web Application Connecting to a MySQL database
PHP-II.
Introduction to Web programming
PHP By Prof. B.A.Khivsara Note: The material to prepare this presentation has been taken from internet and are generated only for students reference and.
Presentation transcript:

Unit 2 MY SQL DATABASE PROGRAMMING

Topics to be Covered: Connecting, Table Creation, Record Insertion, Updation, Multiple database handling.

My SQL Queries DDL CREATE ALTER DROP RENAME TRUNCATE DML SELECT INSERT UPDATE DELETE DCL GRANT REVOKE

My SQL Queries(Contd…) DDL: CREATE: CREATE TABLE table_name ( column_name1 data_type(size), column_name2 data_type(size), column_name3 data_type(size), .... ); ALTER: ALTER TABLE table_name ADD column_name datatype; ALTER TABLE table_name DROP COLUMN column_name; ALTER TABLE table_name MODIFY COLUMN column_name datatype;

My SQL Queries(Contd…) DDL(Contd…) TRUNCATE: What if we only want to delete the data inside the table, and not the table itself? TRUNCATE TABLE table_name; DROP: The DROP TABLE statement is used to delete a table / database. DROP TABLE table_name; DROP DATABASE database_name; RENAME: RENAME TABLE tablename TO newtablename [, tablename2 TO newtablename2];

SELECT columnname,columnname FROM tablename; SELECT * FROM tablename; My SQL Queris(Contd…) DML: SELECT: SELECT columnname,columnname FROM tablename; SELECT * FROM tablename; INSERT: INSERT INTO tablename VALUES (value1,value2,value3,...); INSERT INTO tablename (column1,column2,column3,...) VALUES (value1,value2,value3,...); UPDATE: UPDATE tablename SET column1=value1,column2=value2,... WHERE somecolumn=somevalue; DELETE: The DELETE statement is used to delete records in a table. DELETE FROM tablename WHERE somecolumn=somevalue; DELETE FROM tablename; or DELETE * FROM tablename;

My SQL Queries(Contd…) DCL: GRANT: GRANT privileges ON object TO user; GRANT SELECT, INSERT, UPDATE, DELETE ON contacts TO batchX; REVOKE: REVOKE privileges ON object FROM user; REVOKE DELETE, UPDATE ON contacts FROM batchX;

Other Queries To create a database: create database database_name; To display databases: show databases; To selecting a database use database_name; To display tables: show tables; To structure of a table: describe table_name; show columns from table_name; 8 8

Connection to My SQL Server PHP provides mysqli_connect() function to open a database connection. It takes five parameters. Syntax: connection mysql_connect(server, user, passwd, new_link, client_flag); On successful it returns connection, on failure it returns false.

Connection to My SQL Server (Contd…)

Connection to My SQL Server (Contd…) <html> <head> <title>Connecting MySQL Server</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = ''; $conn = mysqli_connect($dbhost, $dbuser, $dbpass); if(!$conn ) { die('Could not connect: ' . mysqli_error()); } echo 'Connected successfully'; mysqli_close($conn); ?> </body> </html>

Creating a Database <?php // Database connection establishment $con=mysqli_connect('localhost','root',''); // Check connection if (!$con) { echo "MySQL database connection failed:".mysqli_connect_errno(); } // Create database $dbname = “CREATE DATABASE myDB”; if (mysqli_query($con,$dbname)) { echo "Database created successfully"; else{ echo "Error in creating database: " . mysqli_error($con); mysqli_close($con); ?>

Creating a table mysqli_close($con); <?php $con=mysqli_connect("localhost","root","","myDB"); if ( !$con)) { echo "MySQL database connection failed: " . mysqli_connect_error(); } $query = "CREATE TABLE users( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY , name VARCHAR( 25 ) NOT NULL , age INT NOT NULL )"; if (mysqli_query($con,$query)) { echo "Table created successfully"; else{ echo "Error in creating table: " . mysqli_error($con); mysqli_close($con); ?>

Inserting data into a table To insert data into MySQL table, you use SQL INSERT INTO command. Syntax: INSERT INTO table_name (field1, field2 ,...fieldN ) VALUES (value1 , value2 ,... valueN ); To insert string data types , it is required to keep all the values into double or single quote.

POST and GET What is HTTP? The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. HTTP works as a request-response protocol between a client and server. A web browser may be the client, and an application on a computer that hosts a web site may be the server. Example: A client (browser) submits an HTTP request to the server; then the server returns a response to the client.

Example: name1=value1&name2=value2&name3=value3 POST and GET (Contd…) Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand. Example: name1=value1&name2=value2&name3=value3 Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.

GET is used to requests data from a specified resource. POST and GET (Contd…) There are two ways the browser client can send information to the web server. The GET Method The POST Method GET is used to requests data from a specified resource. POST is used to submits data to be processed to a specified resource.

Example: http://www.test.com/index.htm?name1=value1&name2=value2 POST and GET (Contd…) The GET Method: The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. Example: http://www.test.com/index.htm?name1=value1&name2=value2 GET requests can be cached. GET requests remain in the browser history. GET requests can be bookmarked. GET requests have length restrictions (1024 characters ). GET can't be used to send binary data, like images or word documents, to the server. GET requests should never be used when dealing with sensitive data. GET requests should be used only to retrieve data. The PHP provides $_GET associative array to access all the sent information using GET method.

The POST method transfers information via HTTP headers. POST and GET (Contd…) The POST Method: The POST method transfers information via HTTP headers. The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure. POST requests are never cached. POST requests do not remain in the browser history. POST requests cannot be bookmarked. POST requests have no restrictions on data length. The POST method can be used to send ASCII as well as binary data. POST request can be used when dealing with sensitive data. POST request can be used to when the data is to be processed. The PHP provides $_POST associative array to access all the sent information using POST method.

Inserting data into a table (Contd…) <?php // Database connection establishment $con = mysqli_connect("localhost","root","","myDB3"); // Check connection if (!$con) { echo "MySQL database connection failed: " . mysqli_connect_error(); } // Insert $input1 = "INSERT INTO users (id,name,age) VALUES (1,‘ABC',28)"; mysqli_query($con,$input1); mysqli_close($con); ?>

Inserting data into a table through HTML <body> <form action="submit.php" method="post"> <table> <tr> <td>FirstName:</td> <td><input type="text" name="name" ></td> </tr> <tr> <td>Email:</td> <td><input type="text" name="email" ></td> <tr> <td>Message:</td> <td><textarea name="message" cols="40" rows="5" ></textarea></td> <tr> <td><input name="submitBtn" type="submit" value="Submit"></td> </table> </form> </body> </html>

Inserting data into a table through HTML (Contd…) <?php // Database connection establishment $con=mysqli_connect("localhost","root","","mydb"); // Check connection if (!$con) { echo "MySQL database connection failed: " . mysqli_connect_error(); } //CHECKING SUBMIT BUTTON PRESS or NOT. if(isset($_POST['submitBtn'])){ $name=$_POST['name']; $email=$_POST['email']; $message=$_POST['message']; //INSERT QUERY $query = "INSERT INTO contact (name,email,message) VALUES ('$name','$email','$message')"; if(mysqli_query($con,$query)){ echo "Record inserted successfully"; else{ echo "Error in inserting: ".mysqli_error($con); mysqli_close($con); ?>

Inserting multiple rows into a table (Contd…) <?php $con = mysqli_connect("localhost","root","","mydb"); if (!$con) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO contact (name, message, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO contact (name, message, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO contact (name, message, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if (mysqli_multi_query($con, $sql)) { echo "New records created successfully"; else { echo "Error: " . $sql . "<br>" . mysqli_error($con); mysqli_close($con); ?>

Fetching Data Using PHP Script The SQL SELECT command is used to fetch data from MySQL database. You can use one or more tables separated by comma to include various conditions using a WHERE clause, but WHERE clause is an optional part of SELECT command. You can fetch one or more fields in a single SELECT command. You can specify star (*) in place of fields. In this case, SELECT will return all the fields. You can specify any condition using WHERE clause.

Fetching Data Using PHP Script You can use the SQL SELECT command into PHP function mysql_query(). This function is used to execute SQL command and later other PHP functions mysqli_fetch_assoc() & mysqli_fetch_array() can be used to fetch all the selected data. mysql_fetch_assoc() function returns the row as an associative array. mysql_fetch_array() function returns row as an associative array, a numeric array, or both. Both mysql_fetch_assoc() & mysql_fetch_array() functions returns FALSE if there are no more rows.

Fetching Data Using PHP Script (Contd…) mysqli_fetch_array() function takes two arguments: First is the result of select command and the second is the any one of the constant (MYSQL_ASSOC or MYSQL_NUM ). This constant will cause the function to return an array with associative name or numeric index respectively. mysqli_fetch_assoc() function takes one argument that is the result set of select command.

Fetching data from a table through HTML (Contd…) <body> <form action="submit.php" method=“get"> <input name="submitBtn" type="submit" value="Submit"> </form> </body> </html> <?php $con=mysqli_connect("localhost","root","","mydb"); if (!$con) { echo "MySQL database connection failed: " . mysqli_connect_error(); } if(isset($_GET['submitBtn'])){ $query = "select * from contact"; $retval = mysqli_query($con,$query); while($row = mysqli_fetch_array($retval,MYSQL_ASSOC)){ echo $row['name']." ".$row['email']." ".$row['message']."<br>"; mysqli_close($con); ?>

Fetching data from a table through HTML (Contd…) <body> <form action="submit.php" method=“get"> <input name="submitBtn" type="submit" value="Submit"> </form> </body> </html> <?php $con=mysqli_connect("localhost","root","","mydb"); if (!$con) { echo "MySQL database connection failed: " . mysqli_connect_error(); } if(isset($_GET['submitBtn'])){ $query = "select * from contact"; $retval = mysqli_query($con,$query); while($row = mysqli_fetch_array($retval,MYSQL_NUM)){ echo $row[0]." ".$row[1]." ".$row[2]."<br>"; mysqli_close($con); ?>

Fetching data from a table through HTML (Contd…) <body> <form action="submit.php" method=“get"> <input name="submitBtn" type="submit" value="Submit"> </form> </body> </html> <?php $con=mysqli_connect("localhost","root","","mydb"); if (!$con) { echo "MySQL database connection failed: " . mysqli_connect_error(); } if(isset($_GET['submitBtn'])){ $query = "select * from contact"; $retval = mysqli_query($con,$query); while($row = mysqli_fetch_assoc($retval)){ echo $row['name']." ".$row['email']." ".$row['message']."<br>"; mysqli_close($con); ?>

Fetching Data Using PHP Script (Contd…) Releasing Memory: It's a good practice to release cursor memory at the end of each SELECT statement. This can be done by using PHP function mysqli_free_result(). This function takes result set as the parameter. Below is the example to show how it has to be used.

Fetching data from a table through HTML (Contd…) <body> <form action="submit.php" method=“get"> <input name="submitBtn" type="submit" value="Submit"> </form> </body> </html> <?php $con=mysqli_connect("localhost","root","","mydb"); if (!$con) { echo "MySQL database connection failed: " . mysqli_connect_error(); } if(isset($_GET['submitBtn'])){ $query = "select * from contact"; $retval = mysqli_query($con,$query); while($row = mysqli_fetch_assoc($retval)){ echo $row['name']." ".$row['email']." ".$row['message']."<br>"; mysqli_free_result($retval); echo "Fetched data successfully\n"; mysqli_close($con); ?>

Updating a row in a table Syntax: UPDATE table_name SET field1 = new-value1, field2 = new-value2 [WHERE Clause] You can update one or more fields altogether. You can specify any condition using WHERE clause. You can update values in a single table at a time. The WHERE clause is very useful when you want to update selected rows in a table. You can use SQL UPDATE command with or without WHERE CLAUSE into PHP function mysql_query(). Without WHERE clause all the rows are gets effected with the new value.

Updating a row in a table (Contd…) <?php $con = mysqli_connect(“localhost”, ”root”, ””, ”MyDB”); if (!$con) { die("Connection failed: " . mysqli_connect_error()); } $sql = "UPDATE contact SET name='Sree' WHERE email='abc.abc@gmail.com'"; if (mysqli_query($con, $sql)) { echo "Record updated successfully"; else{ echo "Error updating record: " . mysqli_error($conn); mysqli_close($con); ?>

Deleting row(s) from a table DELETE FROM table_name [WHERE Clause] If WHERE clause is not specified , then all the records will be deleted from the given MySQL table. You can specify any condition using WHERE clause. You can delete records in a single table at a time. You can use SQL DELETE command with or without WHERE CLAUSE into PHP function mysql_query().

Deleting row(s) from a table (Contd…) <?php $con = mysqli_connect("localhost", "root", "", "MyDB"); if (!$con) { die("Connection failed: " . mysqli_connect_error()); } $sql = "DELETE FROM contact WHERE email='abc.abc@gmail.com'"; if (mysqli_query($con, $sql)) { echo "Record updated successfully"; else{ echo "Error updating record: " . mysqli_error($conn); mysqli_close($con); ?>

Multiple Database Handling Using PHP API (API – Application Programming Interface), you can connect two different MySQL databases on a single PHP page. You can do this by using two methods: mysql_connect() mysqli_connect() You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for the '$new_link' (fourth) parameter, otherwise the same connection is reused. mysql_select_db() function is used to select the database. Syntax: mysql_select_db(“databasename”, connection-name); You can make multiple calls to mysqli_connect(), by passing “database name” as fourth parameter.

Multiple Database Handling (Contd…) Example using mysql_connect(): $dbh1 = mysql_connect($hostname, $username, $password); $dbh2 = mysql_connect($hostname, $username, $password, true); mysql_select_db('database1', $dbh1); mysql_select_db('database2', $dbh2); To query database 1 pass the first link identifier($dbh1): mysql_query('select * from tablename', $dbh1); To query database2 pass the second link identifier($dbh2): mysql_query('select * from tablename', $dbh2); If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2). mysql_query('select * from tablename');

Multiple Database Handling (Contd…) <?php $db1 = mysql_connect(“localhost”,”root”,””); $db2 = mysql_connect(“localhost”,”root”,””,true); mysql_select_db("mydb1",$db1); $query1 = "select * from contact1"; $text1 = mysql_query($query1,$db1); while($row1=mysql_fetch_assoc($text1)) echo $row1['name']." ".$row1['email']."<br>"; mysql_select_db("mydb2",$db2); $query2 = "select * from contact2"; $text2 = mysql_query($query2,$db2); while($row2=mysql_fetch_assoc($text2)) echo $row2['name']." ".$row2['age']."<br>"; mysql_close($db1); mysql_close($db2); ?>

Multiple Database Handling (Contd…) <?php $db1 = mysqli_connect("localhost","root","","mydb1"); $query1 = "select * from contact1"; $text1 = mysqli_query($db1,$query1); while($row1=mysqli_fetch_assoc($text1)) echo $row1['name']." ".$row1['email']."<br>"; $db2 = mysqli_connect("localhost","root","","mydb2"); $query2 = "select * from contact2"; $text2 = mysqli_query($db2,$query2); while($row2=mysqli_fetch_assoc($text2)) echo $row2['name']." ".$row2['age']."<br>"; mysqli_close($db1); mysqli_close($db2); ?>

Different Methods <?php $db1 = "mydb1"; $db2 = "mydb2"; $link1 = new mysqli("localhost","root","",$db1); if($link1->connect_errno > 0) die("Not connected: ".$link1->connect_error); else echo "Database db1 is connected....."."<br>"; $query1 = "insert into contact1(name,email) values ('sreeee','sreeee@sreeee.com')"; $link1->query($query1); $link2 = new mysqli("localhost","root","",$db2); if($link2->connect_errno > 0) die("Not connected: ".$link2->connect_error); echo "Database db2 is connected....."."<br>"; $query2 = "insert into contact2(name,age) values ('sreenu',30)"; $link2->query($query2); ?>

Different Methods (Contd…) <?php $db1 = "mydb1"; $link1 = new mysqli("localhost","root","",$db1); if($link1->connect_errno > 0) die("Not connected: ".$link1->connect_error); else echo "Database db1 is connected....."."<br>"; $stmt = $link1->prepare("INSERT INTO contact1 (name, email) VALUES (?, ?)"); $stmt->bind_param("ss", $name, $email); $name = "John"; $email = "john@example.com"; $stmt->execute(); echo "New records created successfully"; $stmt->close(); $link1->close(); ?>