PHP Pre Board solution

4th semester

Asian School of Management and Technology

 
Group A
Write some words about php?
PHP: Hypertext preprocessor is a widely used open source general purpose scripting language that is especially suited for web development and can be embedded into HTML.
How can you differentiate static and dynamic website?

Static Website Dynamic Website
Content is fixed and each page is coded in plain HTML and CSS. Content is dynamic which changes according to user’s preferences.
Display the same design and content to every user who visits the website. Offers a unique mix of dynamic contents, multimedia elements and interaction features.
More control and flexibility as each page design is unique. User has complete control over updating the design and changing the content.

What is the uses of foreach in php?
The foreach loop is mainly used for looping through the values of an array. It loops over the array and each value for the content array element is assigned to $value and the array pointer is advanced by one to go the next element is the array.
Syntax:

<?php
foreach (array as $value)
{
//statement
}
?>

What is the uses of strops() function.
The strops() function finds the position of the first occurrence of a string inside another string.
Example:

<?php
echo strpos(“Welcome to BIM Study Notes ! BIM Study Notes helps for BIM Students .” , “BIM”);
?>

What does mysqli_fetch_array() does?
This function is used to fetch the mysql result into a numeric array one row at a time. It returns a numeric array if the data found otherwise it returns null.
Syntax:

<?php
mysql_fetch_array($sql_result);
?>

Differentiate between include(), include_once(), require() and require_once() ?
The include() statement includes and evaluates a specified line ie. It will include a file based in the given path.
The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE.
Require() does the same thing except upon failure it will generate a fatal error and halt the script whereas include() will just give a warning and allow script to continue.
Require_once() will check if the file already has been included and if so it will not include the file again.
Define cookie in php.
A cookie is often used to identify a user. A cookie is small file that the server embeds on the user’s computer requests a page with the browser, it will send the cookie.
Example:

<?php
setcookie(‘user’,’admin’,time()+60*60*24)
echo $_COOKIEE[‘user’];
?>

Give the condition when the variable has local scope.
A variable declared inside a function has a local scope. This variable is unique to this function and can only be accessed within the function.
Example:

<?php
function Hello(){
$txt=”Welcome to BIM Study Notes”;
echo $txt;
}
Hello();
?>

Write statement to connect mysql from PDO in php.
<?php
/*syntax:
new PDO(“host; database”, username, password);
Example:

*/
$con=
new PDO(“mysql:host=localhost;dbname=BIM_Study_Notes”,”root”,” “);
?>

 
In the above example we assume the BIM_Study_Notes is our database name.
What do you know about the die() function in php?
The die() function is an inbuilt function in php used to print message and exit from the current php script.
Example:

<?php
$site="https://bimstudynotes.com/";
fopen($site,"r")
or die ("Unable to connect to $site");
?>

Group B

Exercise Problems:

  1. Make the following html table using PHP. Store values in multi-dimensional associative array.
S_id Name Address Phone
1 Ram Paknajol 422813
2 Shyam Ason 435012
3 Hari Balaju 456921

 

<?php
$item=array(
array('1','Ram','Paknajol','422813'),
array('2','Shyam','Ason','435012'),
array('3','Hari','Balaju','456921')
);
?>
<table align="center" cellspacing="0" cellpadding="10" border="1">
<tr>
<th>S_id</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
<?php
for($row=0; $row<3; $row++)
{
echo"<tr>";
for ($col=0; $col<4; $col++)
{
echo"<td>". $item[$row][$col]."</td>";
}
echo"</tr>";
}
?>
</table>

 
Write the function? List the types of function. Write an example of dynamic function call.
Functions are important tools in any programming language which is define block of statement that perform particular job in a program. Function is a logical unit composed of number of statements group in a single unit. It also defines as section of a unit performing a specific job. Function is code3 snipped that accept values and produce result. Although to be supplied values to produce result. A function in a program is important because of following reasons.

  • Code reusability
  • Manageability
  • Reduce redundancy in programming
  • Logical clarity
  • Easy to divide task among programmer.

User defined Function:
User define function are just a function which are define by a programmer at the time of writing program. A function is just a segment of code that separate rest of code which can perform the similar type of task. The basic syntax for defining user defined function.
<?php

function_name([parameter_list])
{
……………
……………
[return statement]
}
?>

Built-in Function:
These function are already define in the application. These function are used by programmer to design the program. It makes easy to programmer in php, the built-in function are: echo(), print_r(), die(), etc.
The example of dynamic function call:

<?php
function area($l, $b)
{
echo $l*$b;
}
$rect=”area”;
$rect(10,5);
$square=”area”;
$square(10,10);
$shape=”area”;
$shape(5,5);
?>
  1. Write a program to save your personal details into a file “MyFile.csv”.
<?php
$file=fopen("MyFile.csv", 'w');
$name=$_POST[‘name’];
$address=$_POST[‘address’];
$age=$_POST[‘age’];
$arr=array($name, $address, $age);
foreach($arr as $v)
{
fputcsv($file, $v);
}
fclose($f);
echo"sucess";
?>
  1. What is session and why it is used? Give an example of session with session variables and their values.

A session is a way to store information (in variables) to be used across multiple pages. When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
So, Session variables hold information about one single user, and are available to all pages in one application.
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Example:
Login.php

<?php
session_start();
$_SESSION[‘username’]=”admin”;
$_SESSION[‘password’]=”Nepal”;
echo”Session created successfully”;
?>

Home.php

<?php
session_start():
echo”username is:”.$_SESSION[‘username’];
echo”password is:”.$_SESSION[‘password’];
?>

Logout.php

<?php
session_start();
session_unset();
session_destroy();
Echo”logout successfully”;
?>
  1. Write a program to read the string from form and display first and last character of string. Also validate the string for alphabet only.

form.html

<form action="string.php" method="POST">
Enter String:<input type="text" name="txt">
<input type="submit" name="btn">
</form>

string.php

<php
$strtxt=$_POST['txt'];
$s=strlen($strtxt);
$validate=$_POST[‘txt’];
$first=substr($strtxt, 0,1);
$last=substr($strtxt,$s-1,1 );
$pattern_alpha="/[^a-zA-Z\s]/";
echo"first $first";
echo"last $last";
if(preg_match($pattern_alpha,$validate)){
echo "Correct alpha format";
}else{
echo "Incorrect alpha format";
}
?>

Group C

Comprehensive Answer Question:

  1. Write a PHP code for displaying a simple calendar of current months and year.

 

<table border="1" cellspacing='0px' cellpadding='30px' align="center">
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wend</th>
<th>Thur</th>
<th>Fri</th>
<th>Sat</th>
</tr>
<tr>
<?php
$year = $_POST['y'];
$month = $_POST['m'];
$obj = date_create("$year/$month/01");
$start = date_format($obj,"w");
$totaldays = date_format($obj,"t");
echo "<td colspan = $start>&nbsp</td>";
for ($i=1; $i<=$totaldays ; $i++) {
if ($start==7) {
$start=0;
echo "</tr><tr>";
}
$start++;
echo "<td>$i</td>";
}
?>
</tr>
</table>
  1. How can you insert form data safely into database? Write an example.

We can insert form data safely into database by using POST method.
form.php

<form action="string.php" method="POST">
Name:<input type="text" name="name">
Address: <input type=”text” name=”address”
<input type="submit" name="btn">
</form>

insert.php

<?php
$n = $_POST['name'];
$add = $_POST['address'];
$con = mysqli_connect('localhost','root','') or die(mysqli_error($con));
$db = mysqli_select_db($con,"asian") or die(mysqli_error($con));
$q = "insert into student values('','$n','$add')";
$res = mysqli_query($con,$q) or die(mysqli_error($con));
echo "Your entry has been registered";
?>

NCC

  1. What are the basic rules of php?

Every piece of PHP code begins with “<?php”, The way to signify that the PHP code is finished is by adding “?>” at the end.A variable starts with the $ sign, followed by the name of the variable.

  1. What are strpos and strcmp function?

Strops-It is used to find the position of first occurrence of a string inside another string.
Strcmp- It compares two string and returns:
0 – if the two strings are equal
<0 – if string1 is less than string2
>0 – if string1 is greater than string2
 

  1. Explain include and require

If include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function.
The Require () function is also used to put data of one PHP file to another PHP file. If there are any errors then then require () function produces a warning and a fatal error and stops the execution of the script i.e. the script will continue to execute.

  1. Explain array padding with example

Array padding is used to padding (insert) a specified number of elements, with a specified value, into an array. If the specified value is positive then the array is padded on the right, if it is negative then padded on the left.

  1. Explain mysqli_select_db

Change the default database for the connection.

  1. Difference between mysqli_fetch_assoc and mysqli_fetch_array

mysqli_fetch_assoc: Fetch a result row as an associative array.
mysqli_fetch_array: Fetch a result row as a numeric array and as an associative array.

  1. What is a cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

  1. Explain a, x+ mode in file.

Mode (a) – Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist.
Mode (x+) – Creates a new file for read/write. Returns FALSE and an error if file already exists.

  1. How can you get current date and time in PHP?
<?php
echo "Today is " . date("Y/m/d");
?>
  1. Explain SERVER_ADDR and REMOVE_ADDR

SERVER_ADDR is the address of the server PHP code is run on. You don’t need to collect it. REMOTE_ADDR is the one you want. The $_SERVER[‘REMOTE_ADDR’] returns the IP address from which the user is viewing the current page.

  1. Swap two numbers without using third variable.
<?php
$x=10;
$y=5;
$x=$x+$y;
$y=$x-$y;
$x=$x-$y;
echo "The swapped numbers are $x and $y";
?>

Create a form that accepts name, email, phone number and a radio button for gender. Validate required fields and the name must be 6 letters long.

<?php
$namereq='';
$Phonereq='';
$emailreq='';
$genderreq='';
$feereq='';
if($_SERVER['REQUEST_METHOD']=="POST")
{
{
if(empty($_POST['name']))
{
$namereq="Name is required";
}
else
{
$checking=strlen($_POST['name']);
if($checking<=6)
{
$namereq="Length should be 6 letters long or more";
}
}
}
{
if(empty($_POST['Phone']))
{
$Phonereq="Phone no. is required";
$output=1;
}
}
f(empty($_POST['email']))
{
$emailreq="Email is required";
$output=1;
}
if(!isset($_POST['gender']))
{
$genderreq="Gender is required";
}
}
function validation($data)
{
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return  $data;
}
?>
<html>
<head></head
><body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<label>Name:</label><input type="text" name="name" >
<br><u style="color: red;"><?php echo $namereq;?></u><br>
<br>
<label>Phone no:</label><input type="text" name="Phone" >
<br><u style="color: red;"><?php echo $Phonereq;?></u><br>
<br>
<label>Email:</label><input type="text" name="email">
<br><u style="color: red;"><?php echo $emailreq;?></u><br>
<br>
<label>Gender:</label>
Male<input type="radio" name="gender" value="1"> Female <input type="radio" name="gender" value="0">
r><u style="color: red;"><?php echo $genderreq;?></u><br><br>
iinput type="submit" value="Send">
<input type="reset" value="Clear">
</form>
</body>
</html>

Display information of database and database table in table.

<html>
<head>
</head>
<body>
<table border="1px" cellspacing="0.1">
<thead>
<tr>
<th colspan="6" style="border-style: none; padding-bottom:15px; ">List of all Data</th>
</tr>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>DOB</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<?php
$servername_sashil='localhost';
$username_sashil='root';
$password_sashil='';
$database_sashil='QNO9';
$connection_sashil=mysqli_connect($servername_sashil,$username_sashil,$password_sashil,
$database_sashil);
if(!$connection_sashil)
{
die ("Connection error".mysqli_connect_error());
}
$sql="select * from qno9_data";
$result=mysqli_query($connection_sashil,$sql);
if(mysqli_num_rows($result)>0)
{
while($row=mysqli_fetch_assoc($result))
{
echo '<tr>';
echo '<td>'.$row['id'].'</td>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['age'].'</td>';
echo '<td>'.$row['dob'].'</td>';
echo '<td>'.$row['sex'].'</td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
</body>
</html>

 
 

  1. Write the array created in “details.csv”
<?php
$data = array ('Name,College,Faculty,Address',
'Ram,NCC,BIM,Koteshwor',
'Sita,SDC,BBA,Kalanki');
$fp = fopen('details.csv', 'w');
foreach($data as $line){
$val = explode(",",$line);
fputcsv($fp, $val);
}
fclose($fp);
?>
  1. What does mktime do ? Display current date using switch statement.

The mktime() function is an inbuilt function in PHP which is used to return the Unix timestamp for a date.

<?php
$now=date('w');
switch($now){
case 0:
echo "Sunday";
break;
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
}
?>

 
16.
An array is a variable which can hold multiple value of different data type at a time
Example [“Kathmandu”,25,”Nepal”].                                                                                                                                                   An string is a collection of character like “WEB TECHNOLOGY”.

<?php
$arr=array("College"=>"NCC",
"Semester"=>"fourth",
"Exam"=>"preboard",
"Faculty"=>"BIM",
"Course code"=>"IT 219",
"Course Name"=>"Web tech-II"
);
ksort($arr);
print_r($arr);
arsort($arr);
print_r($arr);
?>

Output:-
Array
(
[College] => NCC
[Course Code] => IT 219
[Course Name] => Web tech-II
[Exam] => preboard
[Faculty] => BIM
[Semester] => fourth
)
Array
(
[Exam] => preboard
[Semester] => fourth
[Course Name] => Web tech-II
[College] => NCC
[Course Code] => IT 219
[Faculty] => BIM
)
17.
Session Variables are used because it is the easy and simple way to store the value in variable across the multiple pages.

<?php
session_start();
if(isset($_SESSION['count']))
{
$_SESSION['count']+=1;
}
else
{
$_SESSION['count']=1;
}
echo 'You are visitor number '.$_SESSION['count'];
?>

 

St Xavier’s College

Group A

  • What is a cookies?

Ans: A cookies is a data which is stored in the browser (client side). When a user request to the server it will be delivered along with request. It is used to recognize the user.

  • What is cross site scripting?

Ans: A cross site scripting is a class of security vulnerability where an attacker manages to use a website and tends to deliver potentially malicious Javascript payload to the end user.

  • How validation for Integer and Float is done in PHP?

Ans: Since every input received in a php are in a string form. It must be converted to its original data type. For integer type intval() function and for float type floatval() function is used for validation.

  • What is the use of global keyword and $GLOBALS array?

Ans: Both are used to access global variable.
We can access global variable by using global keyword inside the function.
Eg.
Function sum() {
Global $add;
}
If we use $GLOBALS array then we can directly use it inside the function in $GLOBALS[varname] form.
Eg.
foreach($GLOBALS[‘hobbies’] as $hob)

  • Differentiate between include and require?

Ans:

Include Require
When an error occurs, include will only produce warning and the script will continue. When an error occurs, require will produce fatal error and the script will stop executing.
Syntax:
Include ‘filename’;
Syntax:
Require ‘filename’;

 What is $_SERVER variable?
Ans: $_SERVER variable is a super global variable which holds the information about header, path and script location.
Eg.
$_SERVER[PHP_SELF] : returns the filename of currently executing script.

  • What is epoch time stamp?

Ans: Epoch time stamp is a number of second elapsed since 1 jan 1970 midnight.

  • What does session_start() do?

Ans: Session_start() function is used to start the session. It must be at very beginning. It also helps to declear session variable.

  • What are $_GET and $_POST variables?

Ans: $_GET variable is a super global variable to access the value of a particular field of form and sends it using GET method.
$_POST variable is a super global variable to access the value of a particular field of form and sends it using POST method.

  • How can you accomplish automatic error handling using PEAR in PHP?

An: We can accomplish automatic error handling using setErrorHandling() function and passing PEAR_ERROR_DIE constant.
 
Group B

  • Write a program to manipulate multidimensional associative array in PHP?

Ans: An array within an array is known as multidimensional array. Let us assume we have a districts of Kathmandu valley. (i.e) Kathmandu, Lalitpur and Bhaktapur. Suppose the major places of Kathmandu are New Road, Darbarmarg and Baudha. Similarly Lalitpur has Patan, Jawalakhel and Sanepa and Bhaktapur has Darbar Square and Suryabinayak.

<?php
$city => array(
‘kathmandu’ = > array(‘NewRoad’,’Darbarmarg’,’Baudha’),
‘Lalitpur’ => array(‘Patan’,’Jawalakhel’,’Kupondole’),
‘Bhaktapur’ => array(‘DarbarSquare’,’Suryabinayak’)
);
for( $i=0; $i<count($city); $i++ )
{
for($j=0; $j<count($city[i]); $j++)
{
echo “$arr1[$i][$j]”’
}
echo “<br>”;
}
?>
  • Explain the manipulation of array in a double quoted string with proper example.

Ans: i) If key doesn’t contain other thing than letter, number, and underscore don’t wrap key with quote.
ii) If key contains other character than number, letter and underscore, wrap elements inside array and give quotes.

$arr1 = array( ‘element1’ => ‘value 1’
‘element2’ => ‘value 2’,
‘element 3’ => ‘value 3’,
‘element 4’ => ‘value 4’,
‘element 5’ => ‘value 5’
);
echo “value of element1 is $arr1[element1]”;
echo “value of element3 is $arr1[‘element5’]”;

Assume a database and table of your choice. Design a login form and validate the login form the database. On successful login create login session for the user.

  • Place a checkbox above submit button of Q.no 13 indicating remember me. Set a cookie if the checkbox is checked nad facilitate auto login from the next time.

(Solution of 13 and 14 together.)
Ans:
Index.php

<?php
<html>
<head>
<title>Login</title>
</head>
<body>
<form method=’Post’ action=’valid.php’>
<p>Username:
<input type=’text’ name=’name’>
</p>
<p>Password:
<input type=’password’ name=’pass’>
</p>
<p>Remember me:
<input type=’checkbox’ name=’check’>
</p>
<
<input type=’submit’ value=’login’>
</form>
</body>
</html>
?>

 
Valid.php

<?php
Session_Start();
?>
<?php
$username = $_POST[‘name’];
$password = $_POST[‘pass’];

//1. Connect to DB server and choose DB

$con =mysqli_connect(‘localhost’,’root’,’’,’BIM’);
If(!$con){
die(‘cannot connect to mysql server’.mysqli_connect_error());
}

 
/2) Perform SQL query

$sql = “Select * from user
Where user = $username and password = $password”;//3) use return data
$query = mysql_query($con,$sql);
$row = $mysqli_Fetch_Assoc($query)
If($row[‘username’]==username && $row[‘password’]==password)
{
Set_cookie(‘Username’,’$row[username]’,time() 1*60*60);
Set_cookie(‘Username’,’$row[username]’,time() 1*60*60);
}
echo (“successfully login”);
$_SESSION=(‘Username’,’$row[username]’);
echo “<a href = ‘index.php’>Logout</a>”;
}echo{
echo(“login successful”);
echo “<a href=’index.php’>Try again</a>”;
}
Mysqli_close($con);
?>
  • Mention all the parameters for set_cookie(__)function.

Ans: Cookies are the data that are stored in the browser. When a user request to the server it will be delivered along with request. Cookies is mostly used to recognize the user.
There are three parameter that goes inside set_cookie() function.
Field_name
In this parameter it determines where the cookie is to be set. Mostly in the forms we can see in username and password in which cookies are set.
Cookie value
This parameter determines what value is to be set in cookie.
Time
Time determines the life span of a cookie. To determine the time we use time() function.

The general syntax of set_cookie() function is
Set_cookie (field_name,cookie_Value,time);

Group C

Write a program to set default values and validation of a form consisting of following fields.

  1. Full Name
  2. Username
  3. Password
  4. Email
  5. Faculty (dropdown)
  6. Subject (multiselect dropdown)
  7. Hobbies (checkbox)

 
Upon successful validation insert data into a database table. Assume database name and table as per your convenience.
Ans:

<?php
$gender = array("Male","Female");
$countries = array("Nepal","India","Pakistan","China","Iraq","Afganisthan");
$hobbies = array("Sports","Reading","Music","Dancing");
function showForm($defaults){
global $gender;
echo "<div class='container'>";
echo <<< __form__
<form id='registration' name="f1" method="post" action="$_SERVER[PHP_SELF]">
<h2>Please Fillup to Register</h2>
<table>
<tr>
<td>Name :</td>
<td><input type="text" name="name" value='$defaults[name]'></td>
<input type="hidden" name="__subcheck__" value="1">
</tr>
<tr>
<td>Age : </td>
<td><input type="text" name="age" value='$defaults[age]'></td>
</tr>
<tr>
<td>Weight:</td>
<td><input type="text" name="weight" value='$defaults[weight]'></td>
</tr>
<tr>
<td>Gender:</td>
<td>
__form__;
foreach($gender as $gen){
echo "<input type='radio' name='gen' value='$gen'";
if($gen == $defaults['gen']){
echo "checked = 'checked'";
}
echo ">$gen ";
}
echo <<<__form__
</td>
</tr>
<tr>
<td>Hobbies:</td>
<td>
__form__;
foreach($GLOBALS['hobbies'] as $hobby){
echo "<input type='checkbox' name='hob[]' value='$hobby'";
if(in_array($hobby,$defaults['hob'])){
echo "checked = 'checked'";
}
echo "> $hobby ";
}
echo <<< __form__
</td>
</tr>
<tr>
<td>Country:</td>
<td><select name='country'>
__form__;
foreach($GLOBALS['countries'] as $country){
echo "<option value='$country'";
if($country == $defaults['country']){
echo "selected = 'selected'";
}
echo ">$country</option>";
}
echo <<<__form__
</select></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="pass1" value='$defaults[pass1]'></td>
</tr>
<tr>
<td>Confirm :</td>
<td><input type="password" name="pass2" value='$defaults[pass2]'></td>
</tr>
<tr>
<td colspan="2" align="center"><button type="submit">Register</button></td>
</tr>
</form>
__form__;
echo "</div>";
}
function validateForm(){
$eerrors = array();
//sanitizing the text inputs
$_POST['name'] = trim($_POST['name']);
$_POST['age'] = trim($_POST['age']);
$_POST['weight'] = trim($_POST['weight']);
$_POST['pass1'] = trim($_POST['pass1']);
$_POST['pass2'] = trim($_POST['pass2']);
//checking for empty text fields
if(strlen($_POST['name'])==0 ||
strlen($_POST['age'])==0 ||
strlen($_POST['weight'])==0 ||
strlen($_POST['pass1'])==0 ||
strlen($_POST['pass2'])==0){
$errors[] = "Some text fields are empty";
}
if(strlen($_POST['name']) < 3){
$errors[] = "Name must be atleast 3 characters long";
}
if( ($_POST['age']!=strval(intval($_POST['age']))) || $_POST['age']>120 || $_POST['age']<16 ){
$errors[] = "Age should be a number between 16-120";
}
if( $_POST['weight']!=strval(floatval($_POST['weight']))){
$errors[] = "Weight should be a number may be fractional or integer";
}
if($_POST['pass1'] != $_POST['pass2']){
$errors[] = "Passwords must match";
}
if(strlen($_POST['pass1'])<8){
$errors[] = "Passwords must be at leat 8 characters long";
}
//Checking for valid genders
if(!isset($_POST['gen']) ||!in_array($_POST['gen'],$GLOBALS['gender'])){
$errors[] = "Invalid Gender Input";
}
//Checking for valid country
if(!isset($_POST['country']) || !in_array($_POST['country'],$GLOBALS['countries'])){
$errors[] = 'Invalid country input'. $_POST['country'];
}
/checking for hobbies
if(!isset($_POST['hob']) || !isValidHobbies($_POST['hob'])){
$errors[] = "Some Hobbies are invalid";
}
return $errors;
}
function isValidHobbies($hobbies){
foreach($hobbies as $hobby){
if(!in_array($hobby, $GLOBALS['hobbies'])){
return false;
}
}
return true;
}
function showErrors($errors){
echo "<h3>Please correct the following errors </h3>";
$index = 0;
$classes = array("green","white");
echo "<table>";
foreach($errors as $error){
echo "<tr class='$classes[$index]'><td>$error</td></tr>";
$index = 1-$index;
}
echo "</table>";
}
function processForm(){
$hobbies=implode(',',$_POST['hob']);

 
//1. connect to database server and choose database

$con = mysqli_connect('localhost','root','','bim4a');
if(!$con){
die('connection error'.mysqli_connect_error());
}
$sql = "Insert into exam (Name,Age,Weight,Gender,Hobbies,Country,Password)
values('$_POST[name]',$_POST[age],$_POST[weight],'$_POST[gen]','$hobbies','$_POST[country]','$_POST[pass1]')
";
$query = mysql_query($con,$sql);
if(!$query){
die("query error".mysqli_error($con));
}else{
echo"record inserted successfully";
}
DISP;
}
?>
<html>
<head>
<title>My FOrm</title>
<style>
.green{
background: #9c9;
color: #fff;
font-weight: bold;
}
.white{
background: #fff;
color: brown;
font-weight: bold;
}
form#registration{
background : #99c;
width: 40%;
padding: 10px;
display: inline-block;
border-radius: 20px;
box-shadow: 10px 10px 10px #ccc;
}
input{
color: #aa66ff;
}
div.container{
margin-top: 80px;
}
button[type="submit"]{
padding: 10px;
border: 3px solid;
width: 150px;
border-radius: 10px;
}
button[type="submit"]:hover{
background : 9ff;
order-color: 99f;
cursor: pointer;
}
</style>
</head>
<body>
<?php
$defaults;
if(isset($_POST['__subcheck__'])){
$defaults = $_POST;
if($error = validateForm()){
showErrors($error);
showForm($defaults);
}else{
processForm();
}
}else{
$defaults = array(
'name' => 'Jack Sparrow',
'age' => 45,
'weight' => 55,
'gen' => "Male",
'hob' => array("Sports","Reading","Music"),
'country' => "Iraq",
"pass1" => "hahahaha",
"pass2" => "hahahaha"
);
showForm($defaults);
}
?>
</body>
</html>