Course Title: INTERNET PROGRAMMING AND APPLICATIONS
Date: 20th February 2018
Time Allocated: 3 Hours
INSTRUCTIONS TO CANDIDATES:
Closed Book Examination.
This examination consists EIGHT questions.
Answer all questions in Section A and only three (3) questions from Section B.
All University of Dodoma examination regulations apply.
SECTION A: (40 Marks)
Question One
Choose the letter of the most correct answer. (1 Mark Each)
i. microtime() returns
(a) current Unix timestamp with seconds
(b) current Unix timestamp with nanoseconds
(c) current Unix timestamp with microseconds
(d) None of the above
Answer (Click to show)
(c) current Unix timestamp with microseconds
ii. In which circumstance it is not possible to assign default value to a parameter while declaring a function?
(a) When the parameter is Boolean
(b) When the function is being declared as a member of a class
(c) When the parameter is being declared as passed by reference
(d) When the function contains only one parameter
Answer (Click to show)
(c) When the parameter is being declared as passed by reference
iii. The function _____ automatically transforms newline characters into HTML <br /> tags.
(a) br2nl
(b) nl2br
(c) nlbr
(d) None of the above
Answer (Click to show)
(b) nl2br
iv. By default, PHP stores session data in
(a) The filesystem
(b) A database
(c) Virtual memory
(d) Shared memory
Answer (Click to show)
(a) The filesystem
v. How would you store an array in a cookie?
(a) By adding two square brackets ([]) to the name of the cookie
(b) By using the implode function
(c) It is not possible to store an array in a cookie due to storage limitations
(d) By using the serialize function
(e) By adding the keyword ARRAY to the name of the cookie
Answer (Click to show)
(d) By using the serialize function
vi. What is the correct CSS syntax for making all the <p> elements bold?
(a) p {text-size:bold}
(b) p {font-weight:bold}
(c) style:bold
(d) p{font:bold}
(e) All of the above.
Answer (Click to show)
(b) p {font-weight:bold}
vii. How do you make a list that lists its items with squares?
x. What happens when a form submitted to a PHP script contains two elements with the same name?
(a) They are combined in an array and stored in the appropriate superglobal array
(b) The value of the second element is added to the value of the first in the appropriate superglobal array
(c) The value of the second element overwrites the value of the first in the appropriate superglobal array
(d) The second element is automatically renamed
(e) PHP outputs a warning
Answer (Click to show)
(c) The value of the second element overwrites the value of the first in the appropriate superglobal array
Question Two
(a) What is the value displayed when the following is executed? [2 Marks]
<?php$y = 3;$z = 5;$x = ++$y + $z--;echo $x;?>
Answer (Click to show)
Step-by-step execution:
++$y pre-increment: $y becomes 4, then returns 4
$z-- post-decrement: returns current z(5),thenz becomes 4
$x = 4 + 5 = 9
Output:9
(b) What is the output of the following PHP script? [2 Marks]
<?php$a = 5;$b = 2;$c = $a % $b;echo $c;?>
Answer (Click to show)
Step-by-step execution:
$a % $b = 5 % 2 = 1 (remainder when 5 is divided by 2)
Output:1
(c) What is the output of the following script? [2 Marks]
<?php$a = "b";$b = 20;$a .= 11;echo $$a;?>
Answer (Click to show)
Step-by-step execution:
$a = "b" (string)
$b = 20 (integer)
$a .= 11 concatenates “11” to a→‘a = “b11”`
$$a is a variable variable: $b11 (but $b11 is not defined)
Undefined variable generates a warning and returns NULL
Output: No output (or error/notice)
(d) What will be the output of the following script? [2 Marks]
define('FOO', 10) creates constant FOO with value 10
$array = array(10 => FOO, "FOO" => 20);
Index 10 → value FOO (10)
Index “FOO” → value 20
$array[FOO] = $array[10] = 10
$array[$array[FOO]] = $array[10] = 10
$array["FOO"] = 20
Calculation: 10 * 20 = 200
Output:200
Question Three
Answer the following questions. (2.5 Marks Each)
a) What is a Document Type Definition (DTD)? What DTD do you generally use? Why? What are its Pros and cons.
Answer (Click to show)
Document Type Definition (DTD):
A Document Type Definition (DTD) is a set of markup declarations that define the structure, elements, and attributes of an XML document. It specifies the rules for the document structure, including:
Which elements can appear in the document
The order and nesting of elements
Which attributes are allowed for each element
Commonly Used DTD:
Generally, XHTML 1.0 Strict DTD is commonly used because:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Why:
Enforces clean, well-structured code
Separates content from presentation
Ensures cross-browser compatibility
Promotes accessibility and best practices
Pros of DTD:
Validation: Ensures documents follow defined rules
Sharing: Allows sharing of document structures across organizations
Legacy Support: Supported by many older systems
Namespace Control: Defines which elements and attributes are allowed
Cons of DTD:
Limited Data Types: Only basic string data types
Non-XML Syntax: Uses its own syntax, not XML
No Namespace Support: Limited support for XML namespaces
Less Precise: Cannot define specific data constraints like numbers, dates
No Inheritance: No support for element inheritance
Alternative: XML Schema (XSD) is now preferred as it addresses many DTD limitations, using XML syntax and supporting data types, namespaces, and inheritance.
b) Write a snippet of CSS that will display a paragraph in blue in older browsers, red in newer browsers, green in IE6 and black in IE7.
Answer (Click to show)
/* CSS with browser-specific hacks *//* Default for older browsers - blue */p { color: blue;}/* Newer browsers (standards-compliant) - red */html>body p { color: red;}/* IE6 specific - green */* html p { color: green;}/* IE7 specific - black */*:first-child+html p { color: black;}
Alternative using conditional comments in HTML:
<style type="text/css"> /* Default for all browsers - blue */ p { color: blue; } /* Modern browsers - red */ p { color: red; } /* This will override for modern browsers */</style><!--[if IE 6]><style type="text/css"> p { color: green; }</style><![endif]--><!--[if IE 7]><style type="text/css"> p { color: black; }</style><![endif]-->
c) With the help of a code segment, describe three different ways that can be used to create a JavaScript object.
(b) How can we increase the execution time of a PHP script?
Answer (Click to show)
Methods to Increase PHP Script Execution Time:
<?php// Method 1: Using set_time_limit() function// Set maximum execution time to 300 seconds (5 minutes)set_time_limit(300);// Method 2: Disable time limit (not recommended for production)set_time_limit(0); // 0 means no limit// Method 3: Modify php.ini file (server-wide)// max_execution_time = 300// Method 4: Using ini_set() at runtimeini_set('max_execution_time', 300);// Method 5: For long-running scripts with loops$startTime = time();$maxTime = 300; // 5 minuteswhile (some condition) { // Do work // Check if we're approaching time limit if (time() - $startTime > $maxTime - 10) { // Save state and exit gracefully break; }}// Method 6: For file uploads, also increase post_max_size and upload_max_filesizeini_set('post_max_size', '100M');ini_set('upload_max_filesize', '100M');?>
(c) How can we optimize or increase the speed of a MySQL select query?
Answer (Click to show)
MySQL Query Optimization Techniques:
-- 1. Use indexes on columns used in WHERE, JOIN, and ORDER BYCREATE INDEX idx_lastname ON students(last_name);CREATE INDEX idx_regno ON students(reg_no);-- 2. Select only needed columns, not *-- Instead of:SELECT * FROM students;-- Use:SELECT first_name, last_name, reg_no FROM students;-- 3. Use EXPLAIN to analyze query executionEXPLAIN SELECT * FROM students WHERE last_name = 'Smith';-- 4. Add WHERE clauses to filter dataSELECT * FROM students WHERE program = 'CS' AND year = 2018;-- 5. Use LIMIT for large result setsSELECT * FROM students LIMIT 100;-- 6. Optimize JOIN operationsSELECT s.first_name, s.last_name, c.course_nameFROM students sINNER JOIN enrollments e ON s.id = e.student_idINNER JOIN courses c ON e.course_id = c.idWHERE s.program = 'CS';-- 7. Use appropriate data types-- INT for numbers, VARCHAR for strings, DATE for dates-- 8. Avoid functions in WHERE clauses on indexed columns-- Instead of:SELECT * FROM students WHERE YEAR(enrollment_date) = 2018;-- Use:SELECT * FROM students WHERE enrollment_date BETWEEN '2018-01-01' AND '2018-12-31';-- 9. Use UNION instead of OR when possibleSELECT * FROM students WHERE program = 'CS'UNIONSELECT * FROM students WHERE program = 'IT';-- 10. Consider partitioning for very large tablesCREATE TABLE students ( id INT NOT NULL, reg_no VARCHAR(20), enrollment_date DATE)PARTITION BY RANGE(YEAR(enrollment_date)) ( PARTITION p2017 VALUES LESS THAN (2018), PARTITION p2018 VALUES LESS THAN (2019), PARTITION p2019 VALUES LESS THAN (2020));
(d) How can I know that a variable is a number or not using a JavaScript?
Answer (Click to show)
Checking if a Variable is a Number in JavaScript:
// Method 1: Using typeof operatorlet num = 42;let str = "hello";console.log(typeof num === 'number'); // trueconsole.log(typeof str === 'number'); // false// Method 2: Using isNaN() functionconsole.log(isNaN(42)); // false (is a number)console.log(isNaN("42")); // false (string can be converted to number)console.log(isNaN("hello")); // true (not a number)console.log(isNaN(NaN)); // true// Method 3: Using Number.isFinite() (ES6) - best methodconsole.log(Number.isFinite(42)); // trueconsole.log(Number.isFinite(Infinity)); // falseconsole.log(Number.isFinite("42")); // false// Method 4: Using parseInt/parseFloat and checkingfunction isNumber(value) { return !isNaN(parseFloat(value)) && isFinite(value);}console.log(isNumber(42)); // trueconsole.log(isNumber("42")); // trueconsole.log(isNumber("42.5")); // trueconsole.log(isNumber("hello")); // false// Method 5: Comprehensive functionfunction isValidNumber(value) { // Check if it's actually a number and not NaN/Infinity return typeof value === 'number' && !isNaN(value) && isFinite(value);}console.log(isValidNumber(42)); // trueconsole.log(isValidNumber(NaN)); // falseconsole.log(isValidNumber(Infinity)); // falseconsole.log(isValidNumber("42")); // false// Method 6: Regular expression for numeric stringsfunction isNumericString(value) { return /^-?\d+\.?\d*$/.test(String(value));}console.log(isNumericString("42")); // trueconsole.log(isNumericString("42.5")); // trueconsole.log(isNumericString("-42")); // trueconsole.log(isNumericString("hello")); // false
(e) How can we send mail using JavaScript?
Answer (Click to show)
Sending Mail Using JavaScript:
// Method 1: Using mailto: protocol (opens default email client)function sendMailViaMailTo() { let email = "recipient@example.com"; let subject = "Hello from JavaScript"; let body = "This is a test email sent using JavaScript."; window.location.href = `mailto:${email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;}// Method 2: Using AJAX to call server-side mail script (Recommended)function sendMailViaAjax() { // Create XMLHttpRequest let xhr = new XMLHttpRequest(); xhr.open("POST", "sendmail.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log("Response: " + xhr.responseText); alert("Email sent successfully!"); } }; let data = "to=recipient@example.com&subject=Test&message=Hello"; xhr.send(data);}// Method 3: Using Fetch API (modern approach)function sendMailWithFetch() { let formData = new FormData(); formData.append('to', 'recipient@example.com'); formData.append('subject', 'Test Email'); formData.append('message', 'Hello from JavaScript!'); fetch('sendmail.php', { method: 'POST', body: formData }) .then(response => response.text()) .then(data => { console.log('Success:', data); alert('Email sent successfully!'); }) .catch(error => { console.error('Error:', error); alert('Failed to send email.'); });}// Method 4: Using jQuery AJAXfunction sendMailWithJQuery() { $.ajax({ url: 'sendmail.php', type: 'POST', data: { to: 'recipient@example.com', subject: 'Test', message: 'Hello' }, success: function(response) { alert('Email sent!'); }, error: function(xhr, status, error) { alert('Error: ' + error); } });}
3. Alternative: Using PHP’s PharData for ZIP extraction:
<?php// Alternative using PharData (PHP 5.3+)try { $phar = new PharData($uploadPath); $phar->extractTo($extractPath, null, true); // Extract all files // Get list of files $extractedFiles = []; $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($extractPath, RecursiveDirectoryIterator::SKIP_DOTS) ); foreach ($iterator as $file) { if ($file->isFile()) { $extractedFiles[] = str_replace($extractPath, '', $file->getPathname()); } }} catch (Exception $e) { echo "Error: " . $e->getMessage();}?>
(b) Use the code snippet 1 to:
Code Snippet 1 (HTML):
<!DOCTYPE html><html><head> <title>Sample Page</title></head><body> <h1 class="h">Main Heading</h1> <p id="para1">This is paragraph one with id para1.</p> <p class="h">This is paragraph two with class h.</p> <div class="h">This is a div with class h.</div> <p>This is a normal paragraph.</p></body></html>
(i) Prepare an internal style sheet which will use only group selectors (minimize code) to change the font color of all text to red and change all texts to uppercase. [3 Marks]
Answer (Click to show)
Internal Style Sheet with Group Selectors:
<style type="text/css"> /* Group selector for all elements */ body, h1, p, div { color: red; text-transform: uppercase; } /* Or using universal selector (simplest) */ * { color: red; text-transform: uppercase; }</style>
(ii) Write a style to change the color of the element with id=“para1”, to “red” and align text to center. [3 Marks]
(iii) Write a style to change the color of the element with class=“h”, to “red” and hide the elements when mouse hover it (Use CSS pseudo classes). [4 Marks]
Answer (Click to show)
<style type="text/css"> /* Style for elements with class="h" */ .h { color: red; transition: opacity 0.3s ease; } /* Hide elements when hovered */ .h:hover { opacity: 0; /* Makes element transparent */ visibility: hidden; /* Hides element but preserves layout */ /* OR */ display: none; /* Completely removes element */ }</style>
Question Six
Write the JavaScript code for a basic vocabulary quiz built using Ajax and JSON that allows the user to try to guess the definitions to randomly chosen words from the server. The quiz data comes from a web service named word.php, located on your web server in the same directory as your code. Contact this service with a GET parameter of part for a part of speech such as noun or adjective. It outputs JSON data about a random dictionary word and several possible definitions for the word (at least 2 definitions, of which exactly 1 is correct) in the following format. For example, a request to word.php?part=noun might return:
{ "word": "neophyte", "part": "noun", "choices": [ {"definition": "a person who excels in telling anecdotes", "correct": false}, {"definition": "evenness of mind especially under stress", "correct": false}, {"definition": "a new convert; proselyte", "correct": true}, {"definition": "degree of mixture with base metals; fineness", "correct": false}, {"definition": "rigor, severity", "correct": false} ]}
When the page loads, contact the web service with Ajax. Display the random word and its part of speech in the “word” area. Display all of the possible definitions as buttons in the “choices” area. When the user clicks a button to guess the definition, display an alert message of either “You are correct” or “You are incorrect” appropriately, and then once the alert box is closed, start a new quiz by fetching a new word and displaying it and its definitions to the user. At any time the user can change the part of speech from the select box, which should affect any future words.
The relevant existing HTML in the page is the following:
For the example JSON shown above, the page would look as follows. The three screenshots show the page’s initial state, the state after a button is clicked, and then the state after the alert box is closed and a new word is fetched.
You may assume that the JSON data is valid in the format described previously, and that the .php service is reachable. Do not use any JavaScript libraries such as jQuery or Prototype. [20 Marks]
Answer (Click to show)
Complete JavaScript Solution: vocabulary.js
// vocabulary.js - Ajax Vocabulary Quiz// Global variableslet currentWord = null;let currentPart = 'noun';// Function to create and configure XMLHttpRequestfunction createRequest() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); // Modern browsers } else { // For older IE browsers (IE5, IE6) return new ActiveXObject("Microsoft.XMLHTTP"); }}// Function to fetch new word from serverfunction fetchWord(part) { const wordDiv = document.getElementById('word'); const choicesDiv = document.getElementById('choices'); // Show loading state wordDiv.innerHTML = 'Loading...'; choicesDiv.innerHTML = ''; // Create AJAX request const xhr = createRequest(); // Configure request xhr.open('GET', 'word.php?part=' + encodeURIComponent(part), true); xhr.setRequestHeader('Content-Type', 'application/json'); // Handle response xhr.onreadystatechange = function() { if (xhr.readyState === 4) { // Request complete if (xhr.status === 200) { // Success try { const response = JSON.parse(xhr.responseText); displayWord(response); } catch (e) { wordDiv.innerHTML = 'Error parsing response'; console.error('Parse error:', e); } } else { wordDiv.innerHTML = 'Error loading word. Please try again.'; console.error('HTTP error:', xhr.status); } } }; // Handle network errors xhr.onerror = function() { wordDiv.innerHTML = 'Network error. Please check your connection.'; }; // Send request xhr.send();}// Function to display word and choicesfunction displayWord(data) { currentWord = data; const wordDiv = document.getElementById('word'); const choicesDiv = document.getElementById('choices'); // Display word and part of speech wordDiv.innerHTML = `<strong>${data.word}</strong> <em>(${data.part})</em>`; // Clear previous choices choicesDiv.innerHTML = ''; // Create buttons for each definition choice data.choices.forEach((choice, index) => { const button = document.createElement('button'); button.textContent = choice.definition; button.setAttribute('data-correct', choice.correct); button.setAttribute('data-index', index); // Add styling button.style.display = 'block'; button.style.width = '100%'; button.style.padding = '10px'; button.style.margin = '5px 0'; button.style.backgroundColor = '#f0f0f0'; button.style.border = '1px solid #ccc'; button.style.borderRadius = '5px'; button.style.cursor = 'pointer'; button.style.textAlign = 'left'; button.style.fontSize = '14px'; // Add hover effect button.onmouseover = function() { this.style.backgroundColor = '#e0e0e0'; }; button.onmouseout = function() { this.style.backgroundColor = '#f0f0f0'; }; // Add click handler button.onclick = handleChoiceClick; choicesDiv.appendChild(button); });}// Function to handle choice button clicksfunction handleChoiceClick(event) { const button = event.target; const isCorrect = button.getAttribute('data-correct') === 'true'; // Show alert message if (isCorrect) { alert('✅ You are correct!'); } else { alert('❌ You are incorrect!'); } // After alert closes, fetch new word fetchWord(currentPart);}// Function to handle part of speech changefunction handlePartChange(event) { const select = document.getElementById('part'); currentPart = select.options[select.selectedIndex].text.toLowerCase(); // Fetch new word with selected part fetchWord(currentPart);}// Initialize when page loadswindow.onload = function() { // Add CSS styles addStyles(); // Get select element and add change listener const select = document.getElementById('part'); select.addEventListener('change', handlePartChange); // Fetch initial word fetchWord(currentPart);};// Function to add CSS stylesfunction addStyles() { const style = document.createElement('style'); style.textContent = ` body { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f5f5f5; } h1 { color: #333; text-align: center; margin-bottom: 20px; } fieldset { border: 2px solid #4CAF50; border-radius: 8px; padding: 15px; margin-bottom: 20px; } legend { color: #4CAF50; font-weight: bold; padding: 0 10px; } select { width: 100%; padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 5px; margin-top: 5px; } #word { font-size: 24px; text-align: center; margin: 20px 0; padding: 20px; background-color: white; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); } #choices { margin-top: 20px; } button { transition: all 0.3s ease; } button:hover { transform: translateX(5px); } `; document.head.appendChild(style);}
<?php// word.php - Sample vocabulary web serviceheader('Content-Type: application/json');$part = isset($_GET['part']) ? $_GET['part'] : 'noun';// Sample word database$words = [ 'noun' => [ [ 'word' => 'neophyte', 'part' => 'noun', 'choices' => [ ['definition' => 'a person who excels in telling anecdotes', 'correct' => false], ['definition' => 'evenness of mind especially under stress', 'correct' => false], ['definition' => 'a new convert; proselyte', 'correct' => true], ['definition' => 'degree of mixture with base metals; fineness', 'correct' => false], ['definition' => 'rigor, severity', 'correct' => false] ] ], [ 'word' => 'ephemeral', 'part' => 'noun', 'choices' => [ ['definition' => 'lasting for a very short time', 'correct' => true], ['definition' => 'something that is permanent', 'correct' => false], ['definition' => 'a type of butterfly', 'correct' => false], ['definition' => 'a philosophical concept', 'correct' => false] ] ] ], 'verb' => [ [ 'word' => 'procrastinate', 'part' => 'verb', 'choices' => [ ['definition' => 'to delay or postpone action', 'correct' => true], ['definition' => 'to complete quickly', 'correct' => false], ['definition' => 'to celebrate', 'correct' => false], ['definition' => 'to organize', 'correct' => false] ] ] ], 'adjective' => [ [ 'word' => 'ubiquitous', 'part' => 'adjective', 'choices' => [ ['definition' => 'present everywhere at once', 'correct' => true], ['definition' => 'rare and unique', 'correct' => false], ['definition' => 'very small', 'correct' => false], ['definition' => 'very large', 'correct' => false] ] ] ]];// Select random word from requested partif (isset($words[$part]) && !empty($words[$part])) { $randomIndex = array_rand($words[$part]); echo json_encode($words[$part][$randomIndex]);} else { // Default response echo json_encode([ 'word' => 'example', 'part' => $part, 'choices' => [ ['definition' => 'This is a sample definition', 'correct' => true], ['definition' => 'This is an incorrect choice', 'correct' => false] ] ]);}?>
Question Seven
Write the JavaScript code to add behavior to the following page for finding palindromes. A palindrome is a word that is spelled the same forward as backward, such as “madam” or “Anna”. The page UI allows the user to type a phrase into a text box. The user can click a “Find Palindromes” button to find palindrome words in that phrase. Match case-insensitively; for example, “rotOR” is a palindrome. You may assume that words in the phrase are separated by single spaces and contain only letters. A one-letter word such as “I” is defined to be a palindrome.
Each palindrome found should be inserted as a bullet into a list with the id of palindromes. Every other palindrome (the first, third, fifth, etc.) should be given a gray background color of CC0000. Underneath the list of palindromes you should display text such as “5 total palindrome(s)” in the div with id of count.
The user can optionally specify a minimum and maximum word length by typing integer values into two text boxes with id of min and max respectively. If a minimum is specified, you should include only palindrome words that contain at least that many letters inclusive. If a maximum is specified, you should include only palindrome words that contain at most that many letters inclusive. If the min or max is left blank, the length is unbounded in that direction. For example, a minimum of 3 and a blank maximum finds all palindromes of at least 3 letters. You may assume that the text typed in these boxes will either be blank or a valid non-negative integer, and that max will be ≥ min.
The code should work for multiple clicks of the button. On each click it should clear any previous found information.
Test 1: "madam racecar hello Anna"
Expected: madam (red), racecar (normal), Anna (red)
Count: 3 total palindromes
Test 2: "I am a student at UDOM"
Expected: I (red), a (normal)
Count: 2 total palindromes
Test 3: "rotOR level civic"
Expected: rotOR (red), level (normal), civic (red)
Count: 3 total palindromes
Test 4: With min=3, max=5: "madam racecar Anna"
Expected: madam (red), racecar excluded (too long), Anna excluded (too short)
Count: 1 total palindrome
Question Eight
The University of Dodoma has been asked you to create the student registration form for the online Passport size pictures submission. The form should contain all fields as they appear on figure 1. The page should filter the list of schools based on the selected college all from the database, when student submit the form you are required to rename the picture file (preferably name with six random numbers) and save all student information in the student table. You should upload all pictures to the folder studentPictures located in the system root directory.
Figure 1: Registration Form
Table 1: College
id
college_name
1
CIVE
2
COED
Table 2: School
id
college_id
school_name
1
1
SOI
2
1
SOVE
Table 3: student
id
reg_no
first_name
last_name
picture
1
T/UDOM/2018/00001
Steven
Edward
345612.jpg
[20 Marks]
Answer (Click to show)
Complete Solution: Student Registration with Picture Upload
1. Database Configuration (config.php):
<?php// config.php - Database configuration$db_host = '192.168.2.4'; // MySQL server IP$db_user = 'Cs312';$db_pass = '312Pass';$db_name = 'udom_sr';// Create connection$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);// Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}// Set charset to UTF-8$conn->set_charset("utf8");// Start session for messagessession_start();?>
<?php// get_schools.php - AJAX handler to fetch schools by collegerequire_once 'config.php';header('Content-Type: application/json');if (isset($_POST['college_id'])) { $collegeId = intval($_POST['college_id']); $stmt = $conn->prepare("SELECT id, school_name FROM school WHERE college_id = ? ORDER BY school_name"); $stmt->bind_param("i", $collegeId); $stmt->execute(); $result = $stmt->get_result(); $schools = []; while ($row = $result->fetch_assoc()) { $schools[] = $row; } echo json_encode($schools);} else { echo json_encode([]);}$conn->close();?>
4. SQL Schema (schema.sql):
-- Create databaseCREATE DATABASE IF NOT EXISTS udom_sr;USE udom_sr;-- Create college tableCREATE TABLE IF NOT EXISTS college ( id INT AUTO_INCREMENT PRIMARY KEY, college_name VARCHAR(100) NOT NULL);-- Insert collegesINSERT INTO college (id, college_name) VALUES(1, 'CIVE'),(2, 'COED');-- Create school tableCREATE TABLE IF NOT EXISTS school ( id INT AUTO_INCREMENT PRIMARY KEY, college_id INT NOT NULL, school_name VARCHAR(100) NOT NULL, FOREIGN KEY (college_id) REFERENCES college(id));-- Insert schoolsINSERT INTO school (id, college_id, school_name) VALUES(1, 1, 'SOI'),(2, 1, 'SOVE');-- Create student tableCREATE TABLE IF NOT EXISTS student ( id INT AUTO_INCREMENT PRIMARY KEY, reg_no VARCHAR(50) NOT NULL UNIQUE, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, picture VARCHAR(100) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);-- Insert sample dataINSERT INTO student (reg_no, first_name, last_name, picture) VALUES('T/UDOM/2018/00001', 'Steven', 'Edward', '345612.jpg');