1 / 41

Unit 2 MY SQL DATABASE PROGRAMMING

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:

jgarretson
Télécharger la présentation

Unit 2 MY SQL DATABASE PROGRAMMING

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Unit 2 MY SQL DATABASE PROGRAMMING

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

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

  4. 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;

  5. 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];

  6. 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;

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

  8. 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;

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

  10. Connection to My SQL Server (Contd…)

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

  12. 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); ?>

  13. Creating a table <?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); ?>

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

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

  16. 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. POST and GET (Contd…)

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

  18. 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 $_GETassociative array to access all the sent information using GET method. POST and GET (Contd…)

  19. 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. POST and GET (Contd…)

  20. 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); ?>

  21. Inserting data into a table through HTML <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> <tr> <td>Message:</td> <td><textarea name="message" cols="40" rows="5" ></textarea></td> </tr> <tr> <td><input name="submitBtn" type="submit" value="Submit"></td> </tr> </table> </form> </body> </html>

  22. 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); ?>

  23. 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); ?>

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

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

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

  27. Fetching data from a table through HTML (Contd…) <html> <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); ?>

  28. Fetching data from a table through HTML (Contd…) <html> <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); ?>

  29. Fetching data from a table through HTML (Contd…) <html> <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); ?>

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

  31. Fetching data from a table through HTML (Contd…) <html> <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); ?>

  32. Updating a row in a table Syntax: UPDATEtable_name SET field1 = new-value1, field2 = new-value2 [WHEREClause] • 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.

  33. 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); ?>

  34. 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().

  35. 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); ?>

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

  37. 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');

  38. 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); ?>

  39. 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); ?>

  40. 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); else echo "Database db2 is connected....."."<br>"; $query2 = "insert into contact2(name,age) values ('sreenu',30)"; $link2->query($query2); ?>

  41. 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(); ?>

More Related