What you build in PHP training
A static website can describe a service. A PHP website can accept a request, check it, store it and decide what page to show next. That difference is easier to understand when you follow one request from the browser through the server and into a database. For practice, build an enquiry desk for an imaginary training centre. A learner chooses a subject, leaves an email address and asks for batch information. The resulting data helps staff review requests, yet the public pages never reveal who sent them. Use invented names and example.com addresses while learning.
The enquiry desk gives you several pieces of work a beginner can explain in an interview. You can show a page generated from a PHP array, a form that handles errors, and a database query with bound values. You can also describe where the application keeps a session value and what information it deliberately does not keep there. Ambala learners considering server-side work can use this project to tell whether they enjoy tracing data across a full request. Prior HTML practice helps with the form and labels. The exercises below show what to review if HTML is still new to you.
Set up a local request and identify which layer failed
Create a project folder inside your local PHP server's document root. Put a file called hello.php in that folder with a short PHP statement that prints a fixed message. Start the web server, then request the file using its local HTTP address. Compare the visible message with View Source in the browser. Source shows the response that PHP generated. The original PHP code stays on the server when the server is configured to execute it. For a second check, add an HTML heading above the PHP block and confirm both parts appear in the response.
Local stacks have separate web-server, database and PHP components. A page that responds successfully can still have the wrong database configuration. Conversely, PHP does not run when you open a file directly using a file address in the browser. Work through failures in order: verify that the server responds, verify the requested path, then inspect the PHP error log. If the wrong page appears after saving a change, compare the current browser address with the location of the file you edited. Avoid copying the whole project to another directory while tracing a path error.
Make the first error easy to recognise
Make a lab-only typo by removing a semicolon after an echo statement. Reload, then read the error location in your local log. PHP may report the next line, where it first finds a token it cannot parse. Restore the semicolon and reload. Write the original symptom and the cause in a notebook. You will repeat this habit when failures involve a missing input name or an incorrect table. Keep detailed error display restricted to your local lab. A public page should show an understandable response while diagnostics stay in protected server logs.
Use variables, arrays and functions to generate a page
Imagine the centre has three available options in your exercise. Create an associative array with a stable key for each option, such as php-basics and database-basics. Each key maps to a displayed title. This separation matters because a title can change without invalidating a stored selection. Use a loop to output each course name and its option value. When a form comes back, compare the submitted value with the list of keys. Any value outside that list is invalid even if it looks like a legitimate label.
Start with an exercise that formats a simple course summary. Store weekly practice minutes as an array of integers. Use a function to add them and return the total. Convert the total into hours and remaining minutes only when preparing output. If the inputs are 45, 30 and 55, the total should be 130 minutes, or 2 hours and 10 minutes. The checking question is why a calculated total belongs in a numeric variable while a formatted sentence belongs in a display function. When they are mixed early, later code must pull numbers back out of strings.
<?php
declare(strict_types=1);
function formatStudyTime(array $minutes): string
{
$total = array_sum($minutes);
$hours = intdiv($total, 60);
$remaining = $total % 60;
return sprintf('%d h %d min', $hours, $remaining);
}
echo formatStudyTime([45, 30, 55]);
Try 0, 59, 60 and 61 as single values and predict the response before changing the file. The result for 60 is 1 h 0 min. If the real page accepts this input from a form, validate that each value is a nonnegative integer before calling the function. The example sends a trusted array. Later you will draw the same boundary between a known course list and browser input.
Compare values with an explicit reason
Use a strict comparison when your code expects an exact value and type. For example, when filtering an array of course IDs, convert trusted database values into the type your check uses, then compare them. Test with the string 0 and the integer 0 before trusting a condition built around emptiness. Forms commonly provide strings even for controls labelled as numbers. You might parse a positive integer, reject a missing value and then deliberately work with the resulting integer. Interviewers often ask for the difference between validation and type conversion. This small example lets you show both.
Follow an enquiry form from GET to POST
Build a public enquiry page with three labelled controls for email, subject and message. Give each input a name that your PHP handler expects. The browser sends values by name. For example, a label reading Your email can be connected to an element whose ID is contact-email, while the server reads the value under the name email. Unlabelled controls and mismatched names are easy to overlook if you only test a happy path.
On the first GET request, render the form and build an empty error list. When receiving POST, read the fields, check that each expected input is a string, trim where appropriate and validate the resulting value. Use an email validator, compare the subject key against your allowed choices and check that the message contains meaningful text and fits a length limit. Treat a missing field and a field sent as an array as invalid requests. A user can bypass the browser and submit values your form never offers.
Choose a readable error for each field. A useful message identifies which value needs correction and how to fix it. Render the errors next to the controls or in an error summary linked to them. Keep valid prior values where doing so helps the learner correct the form. Escape values both in plain HTML and in attribute output. A message containing a literal less-than character should display as text. Storing that message using a database parameter solves a different problem from safely displaying it later.
Work through three validation cases
- Valid address, known subject and a short question. Expect the handler to produce an empty error list and reach the database step.
- A correctly formatted email and a made-up subject key such as surprise. Expect a subject error even though email and message are valid. Confirm the count of stored rows stays unchanged.
- A missing email, an otherwise valid course and a message containing only spaces. Expect email and message errors together. Preserve the chosen course on the next view so the learner has less to redo.
For the second case, find how your browser developer tools display form data in the Network panel. Change the value in a local editable copy and see that the server still rejects it. For the third case, examine the validation order. Returning immediately after the email check creates an extra round trip for each remaining mistake. Collecting the errors lets a person fix them together.
Use a session for short-lived state
PHP requests are independent. A session lets the server connect successive requests with a session identifier, commonly carried by a cookie. Call session_start before writing response output. In the enquiry lab, generate a random token when rendering the form, store it in the session, and include it in a hidden form field. When the POST arrives, verify the expected and submitted tokens with a timing-safe comparison. Missing or malformed tokens should fail before validation and insertion. A server-side token is useful even when the form is intentionally available without signing in.
After the submission succeeds, place a short success message in session storage and return a redirect to the confirmation page. The confirmation page reads and removes the message. Now the browser lands on a GET request, so refreshing the confirmation page does not resubmit the POST. This follows the Post/Redirect/Get pattern. Check the Network panel for the original POST, the redirect status and the follow-up GET. A local test with the same form opened twice also helps you understand how shared session data behaves between tabs.
Practise with a visible session counter
Before adding the confirmation flow, write a page that increments a value in the session each time you reload it. Open the same page in a new private browsing window and predict the count there. If the first window has reached four, the new session should usually begin at one. Next, close only the private window and verify that the original browser still continues counting. This makes the distinction between user-visible pages and server-side state concrete. Avoid treating a session ID itself as a public record ID or a reliable identity in application logs.
If you extend the project with a private staff view, add authentication and check authorisation on each protected request. Verify credentials using a password hash and regenerate the session identifier when privileges change. Keep account credentials out of the enquiry exercises. A staff view without built-in protection belongs only in an isolated lab with invented data. A hidden menu link alone cannot protect a page that still has a discoverable URL.
Save the enquiry with a prepared MySQL statement
Design an enquiries table with a generated ID, an email field, a course key, a short message and a creation timestamp. Use a character set that supports the characters learners might enter. Keep the database length limits and application validation limits aligned. In a real site, collect personal data only for a defined purpose and restrict who can review it. In the lab, use addresses such as student@example.com and messages without real contact details.
Connect through PDO and keep database configuration outside tracked publicly shared code. Use a database account with the limited permissions that the feature needs. A public enquiry handler that only creates requests does not need broad administrative rights. Once you have validated the request and verified the token, prepare a statement with named placeholders and execute it with the values. Fixed parts of the query remain in the statement. The placeholders carry data separately.
$query = $pdo->prepare(
'INSERT INTO enquiries (email, course_key, message)
VALUES (:email, :course_key, :message)'
);
$query->execute([
'email' => $email,
'course_key' => $courseKey,
'message' => $message,
]);
Run an exercise with a question containing a quotation mark, such as When does the learner's batch start? The apostrophe should be stored as part of the message. Then try a value that exceeds your permitted length and check that PHP catches it ahead of the insert. When checking a failure, look for evidence in three places in order: the received request, your validation result and the database output. Avoid adjusting the table as a first response to uncertainty about the PHP inputs.
Respond when a dependency is unavailable
A database may reject a connection because the service is stopped, credentials are invalid or a schema was not set up. Reproduce a missing-database condition in the lab with an alternate local configuration. Confirm the public response does not expose credentials, a stack trace or the SQL statement. Log a short diagnostic on the server with enough context to trace the issue. On the form, say the request could not be saved and encourage a later retry. A page should display success only after a successful write. This check is especially helpful when you separate the insert logic into a function.
Read records, sort results and escape display values
While you are learning, review rows in a private database tool or a protected test view populated with sample records. Select specific columns and sort by creation time and ID. Sorting by time alone leaves ties possible when rows share a timestamp. A second sort field yields a predictable order for screenshots and tests. If you add a filter by subject key, check the key and bind it as a parameter. If the user chooses sort order, choose from an allowlist of known alternatives in code. A parameter represents a value, so do not use it as a way to safely interpolate a column name.
Create a lab row with a message that contains angle brackets. Retrieve it and put the value in normal HTML text via htmlspecialchars with a known encoding. The browser should show the characters rather than interpret them as markup. If a teammate suggests fixing this only when inserting, ask what should happen when the same message appears in JSON or an email. Output contexts need different handling. Keeping original valid data and encoding at the boundary where it is displayed makes this easier to reason about.
Build and check an empty result
Choose a valid course key with no enquiries and confirm the view says there are no entries for that course. An empty result is a successful query, so it should not share error wording with a failed database connection. Add one sample enquiry for the key, repeat the filter and check that one record is now visible. This small transition makes a good demo. Mention what request you attempted, which data you expected and how you distinguished no matching records from a query failure.
Debug the project with a short decision tree
When a value is missing, check the browser's submitted field name first. If the name is present, compare the handler's expected type and value. Short labels in a local debug log can help you see which validation branch ran without printing real messages. If the validation branch succeeds and the database is unchanged, verify that you are reading the same database that the handler writes to. Comparing the database name from your development configuration with the active one in your SQL client often reveals this simple mismatch.
A redirect problem needs a separate check. A header must be sent before PHP outputs the response body. Inspect a local warning for its reported leading output line, check for unplanned markup or whitespace, and put the redirect before rendering. End the request after sending a redirect. If the browser refresh creates duplicate enquiries, look at the last request method and whether the code redirected after insertion. Some duplicate submissions can still arrive if a person clicks twice quickly or a client retries. A duplicate check or an idempotency mechanism would be an extension to design separately.
Keep a small repeatable test sheet
- Load the form using GET, use the keyboard to reach all fields, and confirm the hidden token is present in the request after submission.
- Submit a valid sample containing an apostrophe and verify one row with identical message text has been written.
- Submit an incomplete form and confirm the relevant errors are visible, the existing valid input is preserved and row count stays the same.
- Refresh the confirmation page after a valid submission. Confirm the Network panel shows GET and no new database row appears.
- Submit after removing the token in your local test request. Confirm the handler rejects it and repeat with a fresh form to ensure the failure did not disable the valid path.
- Simulate a configuration error locally. Confirm a clear error is shown and the server log gives you enough evidence to solve it.
Refactor the handler after it works
Make a copy of your working lab and mark the boundaries in the request handler. One block reads the incoming fields, another checks the values, another writes the record, and another decides what response to send. Extract a function where the inputs and returns can be named clearly. For example, the validation function can receive the three submitted values and the allowed subject keys, and return an array of errors keyed by field name. Keep redirect decisions at the request level so a function that checks an email address can be tested without starting a browser or opening a connection.
Check this refactor by calling the validator from a small PHP script. Use a learner@example.com address, a valid course key and a short message. Expect no errors. Then call it with a syntactically invalid email and a missing message. Expect two keys in the errors array. Try the valid case again after changing a label in the course list. Since the stored key stays the same, the check should still pass. If you need the current display name later, use the key to read it from the list when rendering the page.
Explain one improvement to a teammate
Open the original handler and the refactored version side by side. Walk through a request that fails validation in both and point out where the response is chosen. Your goal is to show that you improved the organisation while keeping the same result. Record a before-and-after test using the same inputs, not a new scenario that happens to pass. In a second review, look for configuration or business rules copied into multiple functions, such as two different message length limits. Keep one definition and have the relevant check use it. Add a case with a message exactly at the limit and another one character over. A clear small test makes it easier to change that limit after discussing the requirement with someone else.
Turn the enquiry desk into a portfolio project
Record a brief that describes an audience and one important user journey. Example: a Class 12 graduate in Ambala wants to ask about a beginner course, enters a sample question and sees confirmation. Include an overview of how pages, functions and the table fit together. Put a sample schema and a few synthetic records in a setup file so another learner can reproduce your results. Document the PHP and database requirements you used locally. Never include real personal details, passwords or private configuration in screenshots or a repository.
Make your demonstration short enough to follow without setup knowledge. First show the public form and deliberately trigger one error. Then submit correctly and check the stored example. Explain why you treat posted data as untrusted, how you picked the input types and what a prepared statement does. Finish by describing one improvement, such as adding a protected staff filter or counting enquiries by subject. A small application with visible tests makes it easier to explain your contribution than a large copied project with no evidence of how it works.
Prepare for a beginner PHP interview
Where does the PHP code run?
Explain how a browser sends a request, the web server passes it to PHP, PHP generates a response, and the browser renders that response. Use your initial hello.php test to show that the source view contains rendered output. An interviewer may follow up by asking which part sees the database connection. Point out that the browser only receives the result your PHP program sends.
What is the difference between validation and escaping?
Validation asks whether each value meets the rule for its field. For example, check that a course key is one of the known choices. Escaping asks how to present a value safely in a specific context, such as text inside an HTML paragraph. A valid enquiry can contain a character that must be escaped at display time. Explain where these two steps occur in the enquiry project.
How does a prepared statement handle input?
Describe the fixed SQL structure and the values supplied through placeholders. Show the apostrophe test and explain why you expect the exact text to appear in storage. Then describe one case where a placeholder is unsuitable, such as dynamically selecting a column to sort on. In that situation, show a small allowlist of sort options rather than directly copying request text into SQL.
Why use a redirect after a successful POST?
A success redirect is a separate request. Show the browser's request history and explain that the final page can be refreshed without repeating the insertion. Mention how a session message displays confirmation once. A follow-up might ask whether a redirect alone prevents quick repeated submissions. Explain the distinction and discuss a duplicate policy with an example your project could use.
Questions to ask before enrolling in Ambala
Can I start with basic HTML?
Basic markup, labels, input elements and links help you follow the examples. A useful self-check is to create a simple contact form with a name, an email field and a submit button. If that feels unfamiliar, review HTML form structure first. You can learn to think through the PHP logic with a small console script while you build that background.
Is PHP the same as learning WordPress?
PHP is the language used in this course to build server-side features directly. WordPress course practice begins with managing pages, themes and plugins from its interface. If your aim is to create and maintain a local business site, dashboard practice may suit you. If you want to understand the code behind form processing, sessions and database interactions, the PHP path goes deeper into those parts. Describe the kind of work you want to do when enquiring about the batch.
What should I clarify about batches, fees and practice time?
Ask admissions for the current syllabus, start date, regular class timings, total fee and setup requirements. Explain whether you have a computer for home practice and whether you can already create an HTML form. If you are travelling from Ambala Cantt or another nearby area, check the class timing and visit arrangements before booking. Ask how much guided work the batch allocates to PHP forms and MySQL, so you know how the project practice fits your schedule.