Publicité

UNIT V (5).pptx

22 Feb 2023
Publicité

Contenu connexe

Publicité

UNIT V (5).pptx

  1. UNIT V Database Connectivity – MySQL
  2. Contents-Database Connectivity – MySQL Connecting to MySQL – Queries – Fetching Data Sets – Data About Data – Multiple Connections – Creating MySQL Databases with PHP – MySQL Functions – HTML Tables and Database Tables – Complex Mappings – Creating the Sample Tables
  3. Databases and MYSQL Database A database is a collection of data which is stored on a computer Why a database? ● Maintainability ● Scalability ● portability
  4. MYSQL ● MySQL is the most popular database system used with PHP. ● 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 ● MySQL is very fast, reliable, and easy to use ● MySQL uses standard SQL ● MySQL compiles on a number of platforms ● MySQL is free to download and use ● MySQL is developed, distributed, and supported by Oracle Corporation ● The data in a MySQL database are stored in tables. A table is a collection of related data, and it consists of columns and rows.
  5. Connecting to MySQL ● The basic command to initiate a MySQL connection is mysql_connect($hostname, $user, $password); Create database The CREATE DATABASE statement is used to create a database in MySQL.
  6. <?php $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = mysqli_connect($servername, $username, ""); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Create database $sql = "CREATE DATABASE Faculty"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); } mysqli_close($conn); ?>
  7. Queries ● Create table CREATE TABLE statement is used to create a table in MySQL. CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ● Insert data →INSERT INTO statement is used to add new records to a MySQL table INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
  8. Queries ● Select data→ SELECT statement is used to select data from one or more tables The SELECT statement is used to select data from one or more tables: SELECT column_name(s) FROM table_name Or Use the * character to select ALL columns from a table: SELECT * FROM table_name ● Update data UPDATE statement is used to update existing records in a table: UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
  9. Queries ● Delete data DELETE statement is used to delete records from a table: DELETE FROM table_name WHERE some_column = some_value
  10. Example (table creation) <?php $conn = mysqli_connect("localhost","root","","student"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "CREATE TABLE firstyears ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; if (mysqli_query($conn, $sql)) { echo "Table Firstyear created successfully"; } else { echo "Error creating table: " . mysqli_error($conn); } mysqli_close($conn); ?>
  11. Example (insert data) <?php $conn = mysqli_connect("localhost","root","","student"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO secondyear (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
  12. Example (insert multipledata) <?php $conn = mysqli_connect("localhost","root","","student"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO secondyear (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO secondyear (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO secondyear (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if (mysqli_multi_query($conn, $sql)) { echo "New records created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
  13. Example (update data) <?php $conn = mysqli_connect("localhost","root","","student"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "UPDATE secondyear SET lastname='Ramu' WHERE firstname='Mary'"; if (mysqli_query($conn, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($conn); } mysqli_close($conn); ?>
  14. Example (delete data) <?php $conn = mysqli_connect("localhost","root","","student"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // sql to delete a record $sql = "DELETE FROM secondyear WHERE firstname='john' "; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } mysqli_close($conn); ?>
  15. Fetching Data Sets Data can be fetched from MySql tables by executing SQL SELECT statement through PHP function mysqli_query() The fetching functions are as follows: mysql_fetch_row: Returns row as an enumerated array mysql_fetch_object: Returns row as an object mysql_fetch_array: Returns row as an associative array mysql_result: Returns one cell of data mysql_fetch_assoc(): returns the row as an associative array mysqli_data_seek(): it adjusts the result pointer to an arbitrary row in the result set
  16. Example (mysql_fetch_row) <?php $conn = mysqli_connect("localhost","root","","student"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT firstname,lastname FROM thirdyear"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_row($result)) { echo $row[0].$row[1]."<br>"; } } else { echo "0 results"; } mysqli_close($conn); ?>
  17. Example (mysql_fetch_object) <?php $conn = mysqli_connect("localhost","root","","student"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "select firstname, lastname FROM thirdyear"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($obj=mysqli_fetch_object($result)) { echo $obj->firstname.$obj->lastname. "<br>"; } } else { echo "0 results"; } mysqli_close($conn); ?>
  18. Example (mysql_fetch_array) <?php $conn = mysqli_connect("localhost","root","","student"); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "select firstname, lastname FROM thirdyear"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_array($result)) { echo "Name " . $row["firstname"]. $row["lastname"]. "<br>"; } } else { echo "0 results"; } mysqli_close($conn); ?>
  19. Example (mysql_fetch_assoc()) <?php // Create connection $conn = mysqli_connect("localhost","root","","student"); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "select firstname, lastname FROM thirdyear"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "Name " . $row["firstname"]. $row["lastname"]. "<br>"; } } else { echo "0 results"; } mysqli_close($conn); ?>
  20. Example (mysql_data_seek()) <?php // Create connection $conn = mysqli_connect("localhost","root","","student"); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT * from thirdyear"; $result = mysqli_query($conn, $sql); mysqli_data_seek($result,4); $row=mysqli_fetch_row($result); echo $row[1].$row[2].$row[0]; mysqli_close($conn); ?>
  21. Data About Data ● Metadata is “the data about the data.” Anything that describes the database ● The MySQL metadata functions fall into two major categories: ○ Functions that return information about the previous operation only ○ Functions that return information about the database structure in general ● mysqli_insert_id→ returns the auto incremented ID assigned to row of data that inserted ● mysqli_field_count—> function returns the number of columns for the most recent query.
  22. Example (mysql_insert_id) <?php $conn = mysqli_connect("localhost","root","","student"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "CREATE TABLE thirddetai( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; $r=mysqli_query($conn, $sql); $sql = "INSERT INTO thirddetai (firstname, lastname, email) VALUES ('sudha', 'Doe', 'john@example.com')"; $result=mysqli_query($conn, $sql); echo "id is".mysqli_insert_id($conn); mysqli_close($conn); ?>
  23. Example (mysql_field_count) <?php $conn = mysqli_connect("localhost","root","","student"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT * from thirddetail"; $result = mysqli_query($conn,$sql); $c= mysqli_field_count($conn); echo $c; mysqli_close($conn); ?>
  24. Multiple Connections ● Multiple Mysql databases are connected into single web page ● It is useful to access data from multiple databases
  25. Example <?php $link1 = mysqli_connect("localhost", "root", "", "student"); $link2 = mysqli_connect("localhost", "root", "", "mydatabase"); if (!$link1) { die("Connection failed: " . mysqli_connect_error()); } if (!$link2) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT firstname, lastname FROM thirdyear"; $sql1 = "SELECT firstname, lastname FROM secondyear"; $result = mysqli_query($link1, $sql); echo "thirdyear details"; while ($obj = mysqli_fetch_object($result)) { echo $obj->firstname.$obj->lastname."<br>"; } $result1 = mysqli_query($link2, $sql1); echo "secondyear details"; while ($obj1 = mysqli_fetch_object($result1)) { echo $obj1->firstname.$obj1- >lastname."<br>"; } mysqli_close($link1); mysqli_close($link2); ?>
  26. Creating MySQL Databases with PHP ● To create a database from PHP, the user will need to have full CREATE/DROP privileges on MySQL ● when you need to create databases programmatically, the relevant functions are: ○ mysql_create_db(): Creates a database on the designated host, with name specified in arguments ○ mysql_drop_db(): Deletes the specified database ○ mysql_query(): Passes table definitions and drops in this function
  27. Example 1:(database creation and deletion) <?php $linkID = mysql_connect(‘localhost’, ‘root’, ‘sesame’); mysql_create_db(‘new_db’, $linkID); mysql_select_db(‘new_db’); $query = “CREATE TABLE new_table (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, new_col VARCHAR(25))“; $result = mysql_query($query); $axe = mysql_drop_db(‘new_db’); ?>
  28. Example 2:(database creation) <?php $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = mysqli_connect($servername, $username, ""); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Create database $sql = "CREATE DATABASE mydatabase1"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); }mysqli_close($conn);?>
  29. Example 3:(database deletion) <?php $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = mysqli_connect($servername, $username, ""); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = 'DROP DATABASE mydatabase2'; $retval = mysqli_query( $conn,$sql ); echo "database deleted"; mysqli_close($conn); ?>
  30. MySQL data types
  31. MySQL Functions
  32. HTML Tables and Database Tables ● A database table persistently stores information in columns, which have predefined names and types so that the information in them can be recovered later. ● An HTML table is a construct that tells the browser to lay out arbitrary HTML contents in a rectangular array in the browser window
  33. One-to-one mapping ● HTML tables are really constructed out of rows (the <TR></TR> construct), and columns have no independent existence — each row has some number of table datum items (the <TD></TD>) ● Map database fields to HTML rows ● The simplest case of displaying a table is the one in which the structure of a database table or query does correspond to the structure of the HTML table we want to display ● The database entity has m columns and n rows, and we’d like to display an m-by-n rectangular grid in the user’s browser window, with all the cells filled in appropriately.
  34. Example: A single-table displayer ● So let’s write a simple translator that queries the database for the contents of a single table and displays the results on screen. ● Here’s the top-down outline of how the code will get the job done: 1. Establish a database connection. 2. Construct a query to send to the database. 3. Send the query and hold on to the result identifier that is returned. 4. Using the result identifier, find out how many columns (fields) there are in each row. 5. Start an HTML table. 6. Loop through the database result rows, printing a <TR></TR> pair to make a corresponding HTML table row. 7. In each row, retrieve the successive fields and display them wrapped in a <TD></TD> pair. 8. Close off the HTML table. 9. Close the database connection.
  35. Example <?php $global_dbh = mysqli_connect("localhost", "root", ""); mysqli_select_db($global_dbh,"student"); function display_db_table($tablename, $connection) { $query_string = "SELECT * FROM $tablename"; $result_id = mysqli_query($connection,$query_string); $column_count = mysqli_num_fields($result_id); print("<TABLE BORDER=1>n"); while ($row = mysqli_fetch_row($result_id)) { print("<TR ALIGN=LEFT VALIGN=TOP>"); for ($column_num = 0;$column_num < $column_count;$column_num++) print("<TD>$row[$column_num]</TD>n"); print("</TR>n"); } print("</TABLE>n"); }?> <HTML> <HEAD> <TITLE>student details</TITLE> </HEAD> <BODY> <TABLE><TR><TD> <?php display_db_table("thirddetai", $global_dbh); ?> </TD><TD> <?php display_db_table("thirdyear", $global_dbh); ?> </TD></TR></TABLE></BODY></HTML>
  36. Displaying column headers ● It’s conventional in HTML to use the <TH> element for column and/or row headers — in most browsers and styles, this displays as a bold table cell. ● One improvement we can make is to optionally display column headers that are based on the names of the table fields themselves. ● To actually retrieve those names, we can use the function mysql_field_name(). Error checking ● die() →if they fail, an informative message will be printed
  37. Example <?php $global_dbh = mysqli_connect("localhost", "root", "")or die("Could not connect to database"); mysqli_select_db($global_dbh,"student")or die("Could not select database"); function display_db_table($tablename, $connection) { $query_string = "SELECT * FROM $tablename"; $result_id = mysqli_query($connection,$query_string); $column_count = mysqli_num_fields($result_id); print("<TABLE BORDER=1>n"); print("<TR>"); for ($column_num = 0;$column_num < $column_count;$column_num++) { $field = mysqli_fetch_field_direct($result_id, $column_num); print("<TH>"); print($field->name); print ("</TH>"); } print("</TR>n"); while ($row = mysqli_fetch_row($result_id)) { print("<TR ALIGN=LEFT VALIGN=TOP>"); for($column_num=0;$column_num< column_count;$column_num++) print("<TD>$row[$column_num]</TD>n"); print("</TR>n"); }print("</TABLE>n"); }?> <HTML><HEAD><TITLE>student details</TITLE></HEAD> <BODY><TABLE><TR><TD> <?php display_db_table("thirddetai", $global_dbh); ?> </TD><TD> <?php display_db_table("thirdyear", $global_dbh); ?> </TD></TR></TABLE></BODY></HTML>
  38. Complex Mappings ● Every row in the resultset corresponds to a row in the table, and the structure of the code is simply two nested loops. ● Unfortunately, life isn’t often this simple, and sometimes the structure of the HTML table we want to display has a complex relationship to the relational structure of the database tables. ● If we want to do a more complex mapping, we have a choice: ○ we can write more complex display code.
  39. Example <?php $global_dbh = mysqli_connect("localhost", "root", ""); mysqli_select_db($global_dbh,"student"); function display_db_table($tablename, $connection) { $query_string = "SELECT firstname,lastname FROM $tablename ORDER BY firstname"; $result_id = mysqli_query($connection,$query_string); $column_count = mysqli_num_fields($result_id); print("<TABLE BORDER=1>n"); print("<TR><TH>firstname</TH><TH>lastname</TH></TR>"); while ($row = mysqli_fetch_row($result_id)) { print("<TR ALIGN=LEFT VALIGN=TOP>"); for ($column_num = 0;$column_num < $column_count;$column_num++) print("<TD>$row[$column_num]</TD>n"); print("</TR>n"); } print("</TABLE>n"); <HTML> <HEAD> <TITLE>student details</TITLE> </HEAD> <BODY> <TABLE><TR><TD> <?php display_db_table("thirddetai", $global_dbh); ?> </TD><TD> <?php display_db_table("thirdyear", $global_dbh); ?> </TD></TR></TABLE></BODY></HTML>
  40. Example <?php $global_dbh = mysqli_connect("localhost", "root", ""); mysqli_select_db($global_dbh,"student"); function display_db_table($tablename, $connection) { $query_string = "SELECT firstname,lastname FROM $tablename where lastname='Doe' ORDER BY firstname"; $result_id = mysqli_query($connection,$query_string); $column_count = mysqli_num_fields($result_id); print("<TABLE BORDER=1>n"); print("<TR><TH>firstname</TH><TH>lastname</TH></TR>"); while ($row = mysqli_fetch_row($result_id)) { print("<TR ALIGN=LEFT VALIGN=TOP>"); for ($column_num = 0;$column_num < $column_count;$column_num++) print("<TD>$row[$column_num]</TD>n"); print("</TR>n"); } print("</TABLE>n"); <HTML> <HEAD> <TITLE>student details</TITLE> </HEAD> <BODY> <TABLE><TR><TD> <?php display_db_table("thirddetai", $global_dbh); ?> </TD><TD> <?php display_db_table("thirdyear", $global_dbh); ?> </TD></TR></TABLE></BODY></HTML>
  41. Creating the Sample Tables <?php $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = mysqli_connect($servername, $username, $password, "mydatabase"); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // sql to create table $sql = "CREATE TABLE fifthyear ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; mysqli_query($conn,$sql);
  42. $sql = "INSERT INTO fifthyear (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO fifthyear (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO fifthyear (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if (mysqli_multi_query($conn, $sql)) { echo "table is created and New multiple records created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
  43. <!DOCTYPE html> <head> <title>Store Data</title> </head> <body> <center> <h1>Storing Form data in Database</h1> <form action="insert.php" method="post"> <label>First Name:</label> <input type="text" name="firstname" id="firstName"><br> <label>Last Name:</label> <input type="text" name="lastname" id="lastName"><br> <label>gender</label> <input type="radio" name="gender" value='m'>Male <input type="radio" name="gender" value='f'>Female<br> <label>Address:</label> <input type="text" name="address" id="Address"><br> <label>Email Address:</label> <input type="text" name="email" id="emailAddress"><br> <label> country </label> <select name="country"> <option value="india"> india </option> <option value="UK"> UK </option> <option value="US"> US</option> </select><br> <input type="submit" value="Submit"> </form> </center> </body> </html>
  44. <html> <body><center> <?php $conn = mysqli_connect("localhost","root","","mydatabase"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $firstname = $_REQUEST['firstname']; $lastname = $_REQUEST['lastname']; $gender = $_REQUEST['gender']; $address = $_REQUEST['address']; $email = $_REQUEST['email']; $country = $_REQUEST['country']; $sql = "INSERT INTO employee VALUES ('$firstname','$lastname','$gender','$address', '$email','$country')"; if(mysqli_query($conn, $sql)) { echo '<h3> The following data stored in a database successfully </h3>'; echo("$firstname<br>$lastname<br>$gender<br>$ad dress<br>$email<br>$country"); } else{ echo "ERROR:". mysqli_error($conn); } // Close connection mysqli_close($conn); ?> </center> </body> </html>
Publicité