WEB TECHNOLOGIES MID - 1 What Is a Control Structure? In simple terms, a control structure allows you to control the flow of code execution in your application. Generally, a program is executed sequentially, line by line, and a control structure allows you to alter that flow, usually depending on certain conditions. Control structures are core features of the PHP language that allow your script to respond differently to different inputs or situations. This could allow your script to give different responses based on user input, file contents, or some other data.
PHP supports a number of different control structures: ● if ● else ● elseif ● switch ● while ● do-while ● for ● foreach PHP If Statement The if construct allows you to execute a piece of code if the expression provided along with it evaluates to true.
Let's have a look at the following example to understand how it actually works. 1 <?php 2 $age = 50; 3 4 if ($age > 30) 5 { 6 echo \"Your age is greater than 30!\"; 7 } 8 ?> PHP Else Statement In the previous section, we discussed the if construct, which allows you to execute a piece of code if the expression evaluates to true. On the other hand, if the expression evaluates to false, it won't do anything. More often than not, you also want to execute a different code snippet if the expression evaluates to false. That's where the else statement comes into the picture. You always use the e lse statement in conjunction with an if statement. Basically, you can define it as shown in the following pseudo-code.
1 if (expression) 2 { 3 // code is executed if the expression evaluates to TRUE 4 } 5 else 6 { 7 // code is executed if the expression evaluates to FALSE 8 } Let's revise the previous example to understand how it works. 01 <?php 02 $age = 50; 03 04 if ($age < 30) 05 { 06 echo \"Your age is less than 30!\"; 07 } 08 else 09 { 10 echo \"Your age is greater than or equal to 30!\";
11 } 12 ?> So when you have two choices, and one of them must be executed, you can use the i f-else construct. PHP Else If Statement We can consider the e lseif statement as an extension to the i f-else construct. If you've got more than two choices to choose from, you can use the e lseif statement. Let's study the basic structure of the elseif statement, as shown in the following pseudo-code. 01 if (expression1) 02 { 03 // code is executed if the expression1 evaluates to TRUE 04 } 05 elseif (expression2) 06 { 07 // code is executed if the expression2 evaluates to TRUE 08 } 09 elseif (expression3) 10 {
11 // code is executed if the expression3 evaluates to TRUE 12 } 13 else 14 { 15 // code is executed if the expression1, expression2 and expression3 evaluates to FALSE, a default choice 16 } Again, let's try to understand it using a real-world example. 01 <?php 02 $age = 50; 03 04 if ($age < 30) 05 { 06 echo \"Your age is less than 30!\"; 07 } 08 elseif ($age > 30 && $age < 40) 09 { 10 echo \"Your age is between 30 and 40!\"; 11 }
12 elseif ($age > 40 && $age < 50) 13 { 14 echo \"Your age is between 40 and 50!\"; 15 } 16 else 17 { 18 echo \"Your age is greater than 50!\"; 19 } 20 ?> As you can see in the above example, we have multiple conditions, so we've used a series of elseif statements. In the event that all i f conditions evaluate to false, it executes the code provided in the last e lse statement. PHP Switch Statement The switch statement is somewhat similar to the e lseif statement which we've just discussed in the previous section. The only difference is the expression which is being checked. In the case of the elseif statement, you have a set of different conditions, and an appropriate action will be executed based on a condition. On the other hand, if you want to compare a variable with different values, you can use the switch statement. As usual, an example is the best way to understand the s witch statement.
01 <?php 02 $favourite_site = 'Code'; 03 04 switch ($favourite_site) { 05 case 'Business': 06 echo \"My favourite site is business.tutsplus.com!\"; 07 break; 08 case 'Code': 09 echo \"My favourite site is code.tutsplus.com!\"; 10 break; 11 case 'Web Design': 12 echo \"My favourite site is webdesign.tutsplus.com!\"; 13 break; 14 case 'Music': 15 echo \"My favourite site is music.tutsplus.com!\"; 16 break; 17 case 'Photography': 18 echo \"My favourite site is photography.tutsplus.com!\"; 19 break;
20 default: 21 echo \"I like everything at tutsplus.com!\"; 22 } 23 ?> While Loop in PHP The w hile loop is used when you want to execute a piece of code repeatedly until the w hile condition evaluates to false. You can define it as shown in the following pseudo-code. 1 while (expression) 2 { 3 // code to execute as long as expression evaluates to TRUE 4 } Let's have a look at a real-world example to understand how the while loop works in PHP.
01 <?php 02 $max = 0; 03 echo $i = 0; 04 echo \",\"; 05 echo $j = 1; 06 echo \",\"; 07 $result=0; 08 09 while ($max < 10 ) 10 { 11 $result = $i + $j; 12 13 $i = $j; 14 $j = $result; 15 16 $max = $max + 1; 17 echo $result; 18 echo \",\"; 19 }
20 ?> Do-While Loop in PHP The d o-while loop is very similar to the while loop, with the only difference being that the while condition is checked at the end of the first iteration. Thus, we can guarantee that the loop code is executed at least once, irrespective of the result of the while expression. Let's have a look at the syntax of the d o-while loop. 1 do 2 { 3 // code to execute 4 } while (expression); Let's go through a real-world to understand possible cases where you can use the d o-while loop. 01 <?php 02 $handle = fopen(\"file.txt\", \"r\"); 03 if ($handle) 04 { 05 do 06 {
07 $line = fgets($handle); 08 09 // process the line content 10 11 } while($line !== false); 12 } 13 fclose($handle); 14 ?> For Loop in PHP Generally, the f or loop is used to execute a piece of code a specific number of times. In other words, if you already know the number of times you want to execute a block of code, it's the f or loop which is the best choice. Let's have a look at the syntax of the f or loop. 1 for (expr1; expr2; expr3) 2 { 3 // code to execute 4 } The e xpr1 expression is used to initialize variables, and it's always executed. The e xpr2 expression is also executed at the beginning of a loop, and if it evaluates to true, the loop code is executed. After execution of the loop code,
the expr3 is executed. Generally, the e xpr3 is used to alter the value of a variable which is used in the e xpr2 expression. Let's go through the following example to see how it works. 1 <?php 2 for ($i=1; $i<=10; ++$i) 3 { 4 echo sprintf(\"The square of %d is %d.</br>\", $i, $i*$i); 5 } 6 ?> The above program outputs the square of the first ten numbers. It initializes $ i to 1, repeats as long as $ i is less than or equal to 10, and adds 1 to $ i at each iteration. For Each in PHP The f oreach loop is used to iterate over array variables. If you have an array variable, and you want to go through each element of that array, the f oreach loop is the best choice. Let's have a look at a couple of examples.
01 <?php 02 $fruits = array('apple', 'banana', 'orange', 'grapes'); 03 foreach ($fruits as $fruit) 04 { 05 echo $fruit; 06 echo \"<br/>\"; 07 } 08 09 $employee = array('name' => 'John Smith', 'age' => 30, 'profession' => 'Software Engineer'); 10 foreach ($employee as $key => $value) 11 { 12 echo sprintf(\"%s: %s</br>\", $key, $value); 13 echo \"<br/>\"; 14 } 15 ?> https://code.tutsplus.com/tutorials/php-control-structures-and-loops--cms-31999#:~:text=Genera lly%2C%20a%20program%20is%20executed,to%20different%20inputs%20or%20situations. 2)explain form processing in php with example. Form Validation: Form validation is done to ensure that the user has provided the relevant information. Basic validation can be done using HTML elements. For example,
in the above script, the email address text box is having a type value as “email”, which prevents the user from entering the incorrect value for an email. Every form field in the above script is followed by a required attribute, which will intimate the user not to leave any field empty before submitting the form. PHP methods and arrays used in form processing are: ● isset(): This function is used to determine whether the variable or a form control is having a value or not. ● $_GET[]: It is used the retrieve the information from the form control through the parameters sent in the URL. It takes the attribute given in the url as the parameter. ● $_POST[]: It is used the retrieve the information from the form control through the HTTP POST method. IT takes name attribute of corresponding form control as the parameter. ● $_REQUEST[]: It is used to retrieve an information while using a database. Form Processing using PHP: Above HTML script is rewritten using the above mentioned functions and array. The rewritten script validates all the form fields and if there are no errors, it displays the received information in a tabular form. Example:
<?php if (isset($_POST['submit'])) { if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname'])) || (!isset($_POST['address'])) || (!isset($_POST['emailaddress'])) || (!isset($_POST['password'])) || (!isset($_POST['gender']))) { $error = \"*\" . \"Please fill all the required fields\"; } else { $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $address = $_POST['address']; $emailaddress = $_POST['emailaddress']; $password = $_POST['password']; $gender = $_POST['gender']; } } ?> <html> <head> <title>Simple Form Processing</title> </head> <body> <h1>Form Processing using PHP</h1> <fieldset> <form id=\"form1\" method=\"post\" action=\"form.php\"> <?php if (isset($_POST['submit'])) { if (isset($error)) { echo \"<p style='color:red;'>\" . $error . \"</p>\"; }
} ?> FirstName: <input type=\"text\" name=\"firstname\"/> <span style=\"color:red;\">*</span> <br> <br> Last Name: <input type=\"text\" name=\"lastname\"/> <span style=\"color:red;\">*</span> <br> <br> Address: <input type=\"text\" name=\"address\"/> <span style=\"color:red;\">*</span> <br> <br> Email: <input type=\"email\" name=\"emailaddress\"/> <span style=\"color:red;\">*</span> <br> <br> Password: <input type=\"password\" name=\"password\"/> <span style=\"color:red;\">*</span> <br> <br> Gender: <input type=\"radio\" value=\"Male\" name=\"gender\"> Male <input type=\"radio\" value=\"Female\" name=\"gender\">Female <br> <br> <input type=\"submit\" value=\"Submit\" name=\"submit\" /> </form> </fieldset>
<?php if(isset($_POST['submit'])) { if(!isset($error)) { echo\"<h1>INPUT RECEIVED</h1><br>\"; echo \"<table border='1'>\"; echo \"<thead>\"; echo \"<th>Parameter</th>\"; echo \"<th>Value</th>\"; echo \"</thead>\"; echo \"<tr>\"; echo \"<td>First Name</td>\"; echo \"<td>\".$firstname.\"</td>\"; echo \"</tr>\"; echo \"<tr>\"; echo \"<td>Last Name</td>\"; echo \"<td>\".$lastname.\"</td>\"; echo \"</tr>\"; echo \"<tr>\"; echo \"<td>Address</td>\"; echo \"<td>\".$address.\"</td>\"; echo \"</tr>\"; echo \"<tr>\"; echo \"<td>Email Address</td>\"; echo \"<td>\" .$emailaddress.\"</td>\"; echo \"</tr>\"; echo \"<tr>\"; echo \"<td>Password</td>\"; echo \"<td>\".$password.\"</td>\"; echo \"</tr>\"; echo \"<tr>\"; echo \"<td>Gender</td>\"; echo \"<td>\".$gender.\"</td>\"; echo \"</tr>\"; echo \"</table>\"; } } ?> </body>
</html> Output: PHP Form Processing - GeeksforGeeks 3) Create a login Database connection(Insert,delete and update). (580) PHP CRUD Tutorial with MySQL & Bootstrap 4 (Create, Read, Update, Delete) - YouTube ● Open the XAMPP Control Panel. ● Start the Apache server by clicking on the Start button. ● Start the MySQL by clicking on the Start button. ● Create all the files needed for login. ● Create login table in the database using phpMyAdmin in XAMPP. Now, we will create four files here for the login system. 1. index.html - This file is created for the GUI view of the login page and empty field validation.
2. style.css - This file is created for the attractive view of the login form. 3. connection.php - Connection file contains the connection code for database connectivity. 4. authentication.php - This file validates the form data with the database which is submitted by the user. Save all these files in the htdocs folder inside the Xampp installation folder. The detailed description and code for these files are discussed below. index.html First, we need to design the login form for the website user to interact with it. This login form is created using html and also contains the empty field validation, which is written in JavaScript. The code for the index.html file is given below: 1. <html> 2. <head> 3. < title>PHP login system< /title> 4. // insert style.css file inside index.html 5. < link rel = \"stylesheet\" t ype = \"text/css\" href = \" style.css\"> 6. </head> 7. <body> 8. <div i d = \" frm\"> 9. <h1>Login< /h1> 10. < form n ame=\"f1\" action = \"authentication.php\" o nsubmit = \"return validation()\" method = \"POST\"> 11. < p> 12. < label> UserName: </label> 13. < input type = \" text\" i d =\" user\" name = \" user\" / > 14. < /p> 15. < p> 16. <label> Password: </label> 17. <input type = \" password\" id =\"pass\" n ame = \"pass\" / > 18. < /p>
19. < p> 20. < input type = \" submit\" i d = \" btn\" value = \"Login\" / > 21. < /p> 22. </form> 23. </div> 24. // validation for empty field 25. < script> 26. function validation() 27. { 28. var id=document. f1.user.value; 29. var ps= document. f1.pass.value; 30. if(i d.length==\"\" && p s.length==\"\") { 31. alert(\"User Name and Password fields are empty\"); 32. return false; 33. } 34. else 35. { 36. if(i d.length==\"\") { 37. alert(\"User Name is empty\"); 38. return false; 39. } 40. if (ps.length==\"\") { 41. alert(\"Password field is empty\"); 42. return false; 43. } 44. } 45. } 46. </script> 47. </body> 48. </html> After executing the above code on the browser, the login page will appear as below if it does not contain style.css file.
style.css Now, we will create style.css file to provide a more attractive view to the login form. The CSS code for the style.css file is given below: 1. body{ 2. background: #eee; 3. } 4. #frm{ 5. border: solid gray 1px; 6. width:25%; 7. border-radius: 2px; 8. margin: 120px auto; 9. background: white; 10. padding: 50px; 11. } 12. #btn{ 13. color: #fff; 14. background: #337ab7;
15. padding: 7px; 16. margin-left: 70%; 17. } After including above CSS file in index.html, the login form will be like - Database and Table Creation Now, the next step is to create the database and the login table inside the database. ● Access the phpMyAdmin on the browser using localhost/phpmyadmin/ and create a table in the database. Here we will create a database and table using GUI based phpMyAdmin rather than queries execution. ● Click on New and enter the database name and then click on Create button.
● Now we will create a login table in the database. Create a table by name login in the database which you have created earlier.
● Specify the column Name and their Type and Length in the table in which we will store the username and password for the different users and save it by clicking on the save button. ● Click on the insert, from where we can insert the records in columns. So insert the username and password here and click on Go button to save the record.
connection.php Next step is to do the connectivity of login form with the database which we have created in the previous steps. We will create connection.php file for which code is given below: 1. <?php 2. $h ost = \" localhost\"; 3. $u ser = \" root\"; 4. $p assword = ''; 5. $d b_name = \" javatpoint\"; 6. 7. $con = m ysqli_connect( $host, $user, $password, $db_name); 8. if(mysqli_connect_errno()) { 9. die(\"Failed to connect with MySQL: \". mysqli_connect_error()); 10. } 11.?> authentication.php
Now, we have our database setup, so we can go with the authentication of the user. This file handles the login form data that sent through the index.html file. It validates the data sent through the login form, if the username and password match with the database, then the login will be successful otherwise login will be failed. 1. <?php 2. include('connection.php'); 3. $u sername = $_POST['user']; 4. $password = $_POST['pass']; 5. 6. //to prevent from mysqli injection 7. $u sername = stripcslashes( $username); 8. $password = stripcslashes( $password); 9. $u sername = m ysqli_real_escape_string($con, $username); 10. $password = mysqli_real_escape_string($con, $password); 11. 12. $sql = \"select *from login where username = '$username' and password = '$password'\"; 13. $result = m ysqli_query($con, $sql); 14. $r ow = mysqli_fetch_array($result, MYSQLI_ASSOC); 15. $c ount = m ysqli_num_rows($result); 16. 17. if($c ount == 1){ 18. echo \"<h1><center> Login successful < /center></h1>\"; 19. } 20. else{ 21. echo \"< h1> Login failed. Invalid username or password.< /h1>\" ; 22. } 23.?>
Database Connection Create config.php file to connect mysql database with PHP. Check config.php file code below. Insert Data Into MySQL In PHP Here i will insert data in MySQL database using MySQL INSERT statement. MySQL Insert Syntax: ● INSERT INTO `table_name`( c olumn_1,column_2,...) V ALUES (v alue_1,value_2,...) ; Now, Create a new file named i nsert.php in project folder and copy – paste below code inside it. insert.php ● <?php ● ● include 'config.php'; //Database configuration file ● mysqli_select_db( $conn, $db_name) ; ● $sql = \"INSERT INTO users (id, firstname, lastname, email) VALUES (NULL,'Om','Dayal','[email protected]')\"; ● $query = m ysqli_query($ conn, $sql); ● if ( ! $query) {
● echo \" User does not inserted. Error : \" . mysqli_error( $conn); ● } else { ● echo \" User inserted successfully.\"; ●} ● ● ?> Now open your browser and locate this link http://localhost/project/insert.php. If you found message like U ser inserted successfully. then data successfully inserted in database. Description: In the above example, ● First we connect MySQL with PHP using config.php file. ● If you are working with many database then you can use mysqli_select_db() function for select database for particular operation. ● Then we use “INSERT INTO” syntax query of MySQL language for insert data into database. After that we use mysqli_query() function for run MySQL syntax query. ● Finally use if…else… condition to check data is inserted or not. Update Data In MySQL Using PHP Let’s change or update database record info by using MySQL “ UPDATE “ query. You can check more about M ySQL UPDATE query here. Here we use table ID field as
reference field to update the record. See the below example. First of all lets check MySQL Update syntax. MySQL UPDATE Syntax ● UPDATE table_name SET field = new-value WHERE field = condition; Create update.php and copy the below code and paste it inside u pdate.php file. Remember that you can not update single record without any reference field otherwise whole table data will updated. update.php ● <?php ● ● include 'config.php'; ● mysqli_select_db( $conn, $db_name); ● $sql = \" UPDATE users SET firstname = 'OM_new',lastname = 'Dayal_new',email = '[email protected]' WHERE id=1 \"; ● $query = m ysqli_query($conn,$sql); ● ● if( ! $query) ●{ ● echo \"Query does not work.\". m ysqli_error( $ conn) ; die; ●} ● else ●{
● echo \" Data successfully updated\"; ●} ● ● ?> Delete Data In MySQL Using PHP To delete data from database, you can use D ELETE MySQL syntax. Here also you want any reference field to delete data. See the below example for more description. MySQL DELETE Syntax ● DELETE FROM table_name [WHERE Clause] Create a d elete.php file, copy the below code and paste it inside d elete.php file. delete.php ● <?php ● ● include ' config.php'; ● mysqli_select_db($ conn,$db_name); ● $sql = \"DELETE FROM users WHERE id = 1\"; ● $query = m ysqli_query( $conn,$sql) ; ● ● if(! $query) ●{ ● echo \"Query does not work.\".m ysqli_error($ conn) ; die; ●}
● else ●{ ● echo \"Data successfully delete.\"; ●} ● ● ?> Now open your browser and locate the path http://localhost/project/delete.php. If you find message like this D ata successfully delete. Then you have done it. Your data is deleted from database. Check U sers table in PhpMyAdmin. Insert Update Delete in PHP and MySQLi (onlineittuts.com) https://www.javatpoint.com/php-mysql-login-system Select Insert Update Delete in MySQL using PHP tutorial – CodeandTuts 4) Write a php script to add and remove users from MYSQL table ? <?php $servername = \"localhost\"; $username = \" username\"; $password = \"password\"; $dbname = \"myDB\";
// Create connection $conn = n ew mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { d ie(\"Connection failed: \" . $conn->connect_error); } $sql = \"INSERT INTO MyGuests (id,firstname, lastname, email) VALUES (1,'John', 'Doe', 'o[email protected]')\"; $sql = \"INSERT INTO MyGuests (id,firstname, lastname, email) VALUES (2,'Joo', 'Dozy', '[email protected]')\"; $sql = \" INSERT INTO MyGuests (id,firstname, lastname, email) VALUES (3,'Jack', 'Dunk', '[email protected]')\"; if ($conn->query($sql) === TRUE) { echo \"New record created successfully\"; } e lse { echo \" Error: \" . $sql . \"<br>\" . $conn->error; } // sql to delete a record
$sql = \"DELETE FROM MyGuests WHERE id=3\"; if ($conn->query($sql) === TRUE) { e cho \"Record deleted successfully\"; } e lse { echo \"Error deleting record: \" . $conn->error; } $conn->close(); ?> PHP MySQL Insert Data (w3schools.com) PHP MySQL Delete Data (w3schools.com) Explain about dom and sax parsers. XML Parsers An XML parser is a software library or package that provides interfaces for client applications to work with an XML document. The XML Parser is designed to read the XML and create a way for programs to use XML. XML parser validates the document and check that the document is well formatted. Let's understand the working of XML parser by the figure given below:
Types of XML Parsers These are the two main types of XML Parsers: 1. DOM 2. SAX DOM (Document Object Model) A DOM document is an object which contains all the information of an XML document. It is composed like a tree structure. The DOM Parser implements a DOM API. This API is very simple to use. Features of DOM Parser A DOM Parser creates an internal structure in memory which is a DOM document object and the client applications get information of the original XML document by invoking methods on this document object. DOM Parser has a tree based structure. Advantages 1) It supports both read and write operations and the API is very simple to use. 2) It is preferred when random access to widely separated parts of a document is required. Disadvantages 1) It is memory inefficient. (consumes more memory because the whole XML document needs to loaded into memory). 2) It is comparatively slower than other parsers. (580) Difference between DOM and SAX - YouTube
SAX (Simple API for XML) A SAX Parser implements SAX API. This API is an event based API and less intuitive. Features of SAX Parser It does not create any internal structure. Clients does not know what methods to call, they just overrides the methods of the API and place his own code inside method. It is an event based parser, it works like an event handler in Java. Advantages 1) It is simple and memory efficient. 2) It is very fast and works for huge documents. Disadvantages 1) It is event-based so its API is less intuitive. 2) Clients never know the full information because the data is broken into pieces. (580) Difference between DOM and SAX - YouTube XML Parsers - javatpoint 6)explain dtd and explain differences between internal and external dtd. XML DTD - javatpoint (580) XML DTD – Document Type Definition | Internal, External DTD with example in Hindi - YouTube
7)define a xml schema to show how a xml schema is created. XML Schema - javatpoint (580) XML Schemas | XSD with Example | Difference between DTD and XSD in Hindi - YouTube 8)Explain servlet and servlet life cycle. (580) Life Cycle of Servlet|| Servlets in Telugu Lecture-3 - YouTube (580) Introduction to Servlets|| Servlets in Telugu Lecture-1 - YouTube 9)Explain servlet with example and deploying steps. Servlet Example : Steps to create a servlet example - javatpoint (580) Deploying a servlet - YouTube Steps to Create Servlet Application using Tomcat server | Studytonight
Search
Read the Text Version
- 1 - 37
Pages: