SEC S20W4 | Introduction to PHP Part - 2

in dynamicdevs-s20w4 •  2 months ago 
Hello Everyone !

I am @hudamalik20 from Pakistan. I hope you all are doing well and having a great time. Today, I am excited to take part in SEC S20W4 | Introduction to PHP Part - 2, organized by @starrchris ,So let's start.

Blue Geometric Business YouTube Thumbnail_20241002_101818_0000.png

Designed by me , edited on Canva

image.png

Section 1: Theoretical Questions


1.Explain in detail what exceptions are, what they are used for, and how they handle errors in PHP. Include an example of using the try and catch blocks.


Exceptions in PHP are a way to handle unexpected errors that may occur during code execution. Instead of letting the program crash, we use certain keywords like try, catch, finally, and throw to manage the error gracefully.

  • Try Block: In PHP, when we expect some error might occur, we write that part of the code inside the try block.

  • Catch Block: The catch block is used to handle the error that occurs inside the try block. If an error (exception) happens, the catch block is executed.

  • Throw: This keyword is used to create an exception manually. We can throw an error when something goes wrong and handle it in the catch block.

p1.PNG

For every try block, there must be at least one catch or finally block. If an exception is not handled (no catch block), PHP will generate a fatal error and stop the execution of the program.

So these are used to handle those parts of the code where an unexpected error might occur. We handle these errors using the try catch combination. The code inside the try block is executed, and if an error occurs, it is caught by the catch block, which can show an error message or take another action.

So In this example:

  • I define a function divide() that checks if I am dividing by zero. If so, it throws an exception.
  • The try block attempts to execute the divide(10, 0) function. Since dividing by zero is not allowed, an exception is thrown.
  • The catch block catches the exception and displays the error message "Cannot divide by zero".This way, exceptions help me control the flow of the program even when errors occur.

image.png


2.What are six common types of PHP errors? Provide examples for each.


Parse Error:
A Parse Error, also known as a Syntax Error, occurs when there's a mistake in the code structure, making it difficult for PHP to understand and execute. In this example, I've missed a semicolon at the end of the echo statement:

p2.PNG

PHP requires proper syntax, like adding semicolons to separate statements. Because I forgot the semicolon here, PHP will throw a Parse Error when the code runs. It will specifically point out where the issue is, showing a message indicating that something is wrong at or near the line where the mistake happened. This helps in quickly identifying and fixing the error.


Fatal Error:
A Fatal Error occurs in PHP when the script tries to perform an action that is not possible, such as calling a function, class, or including a file that does not exist in the program. This kind of error typically happens due to misspelling the function name or forgetting to define the function before calling it.

When a fatal error is encountered, the PHP script stops executing, and no further code is run. This can disrupt the entire functionality of the program, and PHP throws the fatal error to notify the issue.

p3.PNG

In this case, the script is trying to call nonExistentFunction(), which hasn't been defined anywhere in the program. PHP will immediately throw a fatal error and stop executing the rest of the code. The error message will indicate that the function does not exist, and PHP won't proceed beyond this point until the error is resolved.


Warning Error:
A Warning Error in PHP occurs when the script encounters a problem, but it does not prevent the execution of the code. Unlike fatal errors, a warning doesn't stop the script; it only shows a message indicating the issue while allowing the script to continue running.

Although the program continues, it's important to fix these warnings to avoid unexpected behavior in the long run. Warnings are non-fatal errors and are typically related to issues such as including files that don’t exist or improper usage of functions.

p4.PNG

In this case, PHP will show a warning because it cannot find non_existent_file.php. However, the script will continue to execute, and you will see the message "This will still execute even after the warning." despite the warning being displayed.


Notice Error:
A Notice Error in PHP is a minor issue that occurs when something is not entirely right with the code, but it doesn't stop the script from executing. This type of error commonly arises when trying to use an undefined variable, meaning the variable hasn't been initialized before being used.

While notice errors don't significantly impact the execution of the code but a good practice to fix them to avoid any unexpected behavior in the program.

p5.PNG

In this case, PHP will throw a notice error because $undefinedVariable was never defined or initialized. Despite the notice, the script will continue to execute.


Deprecated Error:
A Deprecated Error in PHP occurs when we use an outdated function or feature that is no longer recommended for use. As PHP evolves, newer functions and features are introduced, while older ones may become obsolete.

When we use these deprecated functions, PHP issues a warning, advising us to update our code to use the latest alternatives.

p6.PNG

In this code snippet, we use the split() function, which is deprecated. When we execute this code, PHP generates a deprecated error, signaling that this function should be replaced with a more current alternative, such as explode(). This warning helps us ensure that our code remains compatible with future versions of PHP and allows us to take advantage of improved features.


Undefined Index Error:
An Undefined Index Error occurs when we try to access an index in an array that does not exist. This type of error is not very noticeable but commonly happens when working with arrays. An index refers to the position of an element within the array.

p7.PNG

In this example, we have an array called $fruits that stores two elements: 'apple' at index 0 and 'orange' at index 1. However, when we try to access $fruits[2], we encounter an Undefined Index Error because there is no third element in the array. We only have two indexes available: 0 and 1. This error indicates that we are trying to access an index that does not exist, which can lead to unexpected results in our program.

image.png


3.Describe three personal experiences with errors in PHP coding.


Syntax Error (Parse Error)

One of the most frequent errors I've encountered while coding in PHP is a syntax error, also known as a parse error. This typically happens when there’s a missing semicolon or a typo in the code, which prevents the PHP interpreter from parsing the script correctly.

For instance, once I forgot to add a semicolon at the end of an echo statement. Here’s an example:

In this case, PHP threw a parse error, halting the execution of the script and pointing to the line where the mistake occurred. I quickly realized that missing a semicolon caused the issue, added it back, and the script ran fine.

Now i always check for missing semicolons and typos in the code. Syntax errors are simple but can be frustrating.


Fatal Error

Another error I often encountered is a fatal error, which occurs when I try to call a function that hasn’t been defined or when a class does not exist. This error is more serious because PHP immediately stops execution when it occurs.

p3.PNG

In this case, PHP throws a fatal error, telling me that the nonExistentFunction() is undefined. The program execution stops entirely, which means the script won’t run further until I either define the function or remove the call to it.

Now I make sure to define all functions or include necessary files before calling them in the code.

image.png


Undefined Variable Error (Notice Error)
A notice error often occurs when I try to use a variable that hasn’t been initialized yet. It doesn’t stop the script from running, but PHP will throw a warning message, and the output might not be what I expect.

In this PHP will throw a notice error, stating that $undefinedVariable is undefined. The script will still continue to run, but this warning can help catch potential issues, especially when working with variables that are supposed to hold important values.

Always initialize variables before using them in the code to avoid notice errors.

Each of them has shown me the importance of writing clean and correct code, handling variables properly, and making sure all necessary components are defined before they are used.

image.png


4."Explain the include syntax in PHP and its benefits."


The include statement in PHP allows us to merge one PHP file into another. This means we can add specific files that we have created in our code to another PHP file, which makes it easier to manage our code.

When we build a website, we often have common elements like headers, footers, menus, and database connection scripts that we want to use on multiple pages. Instead of writing the same code for the header and footer on each page, we can use the include statement to access these common files.

php
include('header.php');

p8.PNG

p9.PNG

p10.PNG

p11.PNG

Benefits of Using include

  1. Code Reusability: As I mentioned earlier, we can reuse the same header and footer on multiple pages. This reduces the amount of code we have to write.

  2. Easy Maintenance: When we need to update the header or footer, we only change it in one place. This saves us time because we don’t have to update every single page. The changes will automatically reflect everywhere we used include.

  3. Organized Code: By using include, we can divide our code into smaller parts. For example, we can create separate files for the header, footer, and navigation menu. This makes our code easier to read and manage.

  4. Reduced Duplication: Since we are not copying and pasting the same code in different files, we avoid duplication. We can keep our code clean and simple by just including the necessary files.

image.png


5."How do you connect PHP to a database? Describe the process and provide an example."


I made the connection to the database using XAMPP local server, with my database name being f21:

I first launched XAMPP and started the Apache and MySQL modules. Apache runs the local server, while MySQL manages the database.

After starting MySQL in XAMPP, I went to phpMyAdmin (accessible via http://localhost/phpmyadmin/), . I created a new database named f21. This is where I will store my data.

d1.PNG

Next, I wrote the PHP code to connect to the f21 database. I used the following details:

  • Server Name: Since I am using XAMPP locally, the server name is localhost.
  • Username: In XAMPP, the default username for MySQL is root.
  • Password: There is no password set by default in XAMPP, so I left it blank ("").
  • Database Name: The name of my database is f21.
    I used the mysqli object in PHP to establish the connection. The code I wrote included the server name, username, password, and database name.

p12.PNG

p13.PNG

After creating the connection, I included a check to see if the connection was successful. If there was an error, PHP would output an error message using connect_error. Otherwise, it would display a success message:

Finally, I saved the PHP file in the htdocs folder inside the XAMPP directory. To test the connection, I opened my browser and navigated to the file, using http://localhost/BSIT/database.php. The script successfully connected to the database and displayed the message "Connected successfully".

I did connection to my f21 database using PHP on the XAMPP local server. The connection was established using the default settings of XAMPP for MySQL, and I was able to manage and query the database through PHP code.

image.png


Section 2: Practice Questions :

1.-Page with include: Create a PHP page (learn.php) and use the include syntax to import the header, navigation bar, sidebar and footer.

How I Created the Page Using include in PHP

To create the learn.php page, I used the include statement to separate the different sections of the webpage, such as the header, navigation bar, sidebar, and footer, into individual PHP fils , helps in reusing the code and keeping the structure clean.

s1-1.PNGs2.PNG
s3.PNGs4.PNG

I created different files for each section:

  • header.php for the top header section.
  • navbar.php for the navigation bar.
  • sidebar.php for the sidebar section on the left.
  • footer.php for the footer at the bottom.

In the learn.php file, I used the include statement to add each of these components at their respective positions. This made it easy to structure the webpage by including each section in the main page.

s5.PNGs6.PNG
s7.PNGs8.PNG

s9.PNG

I applied different background colors, centered the text within each section, and styled them to make the webpage look distinct and organized.

  • The navigation bar is displayed horizontally, styled with no list markers.
  • The sidebar is positioned on the left with a vertical layout, making it easy to navigate.
  • Each section has its own color and layout to differentiate it visually.

s10.PNG

s11.PNG

By using include, I can easily manage and update each section without having to modify the whole page every time!

image.png

2.-Database for Registration Page: Create a database capable of storing the data for a registration page.

To store user data for the registration page, I created a new database in MySQL. Here's the step-by-step process I followed:

d1-1.PNG

I first opened XAMPP and ensured that both Apache and MySQL servers were running.

d2.PNG

I opened my web browser (Google Chrome) and typed localhost/phpmyadmin to access the phpMyAdmin interface.

d3.PNG

In phpMyAdmin, I clicked on the "New" button to create a new database. I named this database registration to store the data from my registration page.

d4.PNG

d5.PNG

Inside the registration database, I created a new table named users with the following columns:

  • ID (Primary Key, Auto Increment)
  • Username (VARCHAR, to store usernames)
  • Password (VARCHAR, to store passwords)
  • Email (VARCHAR, to store user email addresses)

I set appropriate lengths for each field, ensuring that the ID was auto incremented so that it would generate automatically for each new user entry.

After completing these steps, my database was successfully set up, and it's now ready to store the registration data!


image.png

3.-Registration Page: Create a PHP registration page to save the data of five students in a database.


I started by designing a simple HTML form with two fields: username and password. This form collects the user's data and sends it to a PHP script for processing.

d6.PNG

d7.PNG

I created a PHP script (register.php) that connects to my MySQL database named registration. The script is responsible for processing the form data and saving it to the database.

d8.PNG

When the form is submitted, the data for the username and password is sent to the PHP script using the POST method. I captured this data in PHP variables and used a prepared statement to insert it into the users table in the database.

d9.PNG

I ensured that each new registration adds a row to the users table with the provided username and password. This way, I could store the information of multiple users securely in the database.

d10.PNG

After setting everything up, I tested the registration page by entering different usernames and passwords. The PHP script successfully inserted the data into the database, confirming the form was working correctly.


image.png

4.-Login Page: Create a PHP login page that verifies the login information with the ones stored in the database and redirects the user if successful.


To create the PHP login page that checks the username and password from the database, I followed these steps:

I started by creating an HTML form where users can enter their username and password. This form was simple, having two input fields (for username and password) and a submit button. The form data is sent to a PHP script for validation.

f1.PNG

I created a PHP script (login.php) that connects to my MySQL database named registration. The script is responsible for verifying the user's credentials against the data stored in the database.

f2.PNG

f3.PNG

When the user submits their username and password, the form sends the data using the POST method to the PHP script. I captured this input in variables $user and $pass.

f4.PNG

I used a prepared statement in PHP to safely check if the entered username and password match any record in the users table in the database. If the username and password match an entry, it means the user credentials are correct.

f5.PNG

  • If the credentials match, the PHP script echoes: "Successfully logged in. Welcome home!", indicating the user has successfully logged in.
  • If the credentials don't match, the script displays an error message: "Invalid username or password. Please try again."

I tested the login page by entering various combinations of usernames and passwords, ensuring that the login system correctly identifies valid and invalid credentials. When the credentials were correct, the message "Successfully logged in. Welcome home!" was displayed, and for incorrect entries, it showed incorrect password or email.


That's it from today's blog I hope you will like it. With best wishes ❤️. Now I like to invite @ahsansharif, @fombae and @josepha to participate in this amazing contest.

Thanks alot for reading ❤️🤗 .

My introduction post

Regards : @hudamalik20 .

image.png

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
Loading...

Upvoted! Thank you for supporting witness @jswit.

Upvoted. Thank You for sending some of your rewards to @null. It will make Steem stronger.

This post has been upvoted/supported by Team 5 via @httr4life. Our team supports content that adds to the community.

image.png

Thank you so much for your support 🤗💞.

Congratulations, your post has been upvoted by @scilwa, which is a curating account for @R2cornell's Discord Community. We can also be found on our hive community & peakd as well as on my Discord Server

Manually curated by @ abiga554
r2cornell_curation_banner.png

Felicitaciones, su publication ha sido votado por @scilwa. También puedo ser encontrado en nuestra comunidad de colmena y Peakd así como en mi servidor de discordia

hi, I appreciate the good job you did on the registration page. I don’t understand why, when the contest says that the registration page allows saving five students, I created five forms to save five students at the same time! Haha. I invite you to take a look at the registration page I created
https://steemit.com/hive-167213/@kafio/sec-s20w4-or-or-introduction-to-php-part-2

Thank you for your kind words. I appreciate your feedback. Actually, I interpreted the contest instructions as saving the data of five students directly into the database, rather than creating five separate forms. My registration page handles all the data at once and stores it in the database.,thanks for your comment wish you success 💖🤗🌸.