PHP and Mysql Exam
PHP and Mysql Exam
Program:
PHP v7.4.30
Directories:
Classes
|_ Process.php
|_ View.php
view
|_ template
|_ promo.phtml
index.php
Source:
Classes/Process.php
<?php
namespace Classes;
class Process
{
/**
* @var array[]
*/
protected $data;
/**
* @var array[]
*/
protected $bestDeal;
/**
* @return $this
*/
public function execute() {
$this->findBestDeal();
return $this;
}
/**
* @return $this
*/
protected function loadData() {
$this->data = [
[
"promo" => "1",
"quantity" => 70,
"price" => 35
],
[
"promo" => "2",
"quantity" => 100,
"price" => 30
]
];
return $this;
}
/**
* @return $this
*/
protected function findBestDeal() {
foreach ($this->data as $item) {
if (empty($this->bestDeal) || $this-
>compareToCurrentBestDeal($item)) {
$this->bestDeal = [
"promo" => $item["promo"],
"price_per_item" => $item["price"]/$item["quantity"]
];
}
}
return $this;
}
/**
* @param $promo
* @return bool
*/
protected function compareToCurrentBestDeal($promo) {
return $this->bestDeal["price_per_item"] >
$promo["price"]/$promo["quantity"];
}
/**
* @return array[]
*/
public function getBestDeal() {
return $this->bestDeal;
}
/**
* @return array[]
*/
public function getData() {
return $this->data;
}
}
Classes/View.php
<?php
namespace Classes;
class View {
/**
* @var Process
*/
private $process;
/**
* @return $this
*/
public function render() {
$this->process->execute();
return $this;
}
/**
* @return array[]
*/
public function getBestDeal() {
return $this->process->getBestDeal();
}
/**
* @return array[]
*/
public function getData() {
return $this->process->getData();
}
}
view/template/promo.phtml
<?php
$items = $this->getData();
$bestDeal = $this->getBestDeal();
foreach ($items as $key => $item): ?>
<div class="promo-deals">
<span>Buy <?=$item["quantity"]?> for</span>
<strong>$<?=$item["price"]?></strong>
<?php if($bestDeal["promo"] == $item["promo"]): ?>
<sup><i>BEST DEAL</i></sup>
<?php endif ?>
</div>
<br/>
<?php endforeach;
index.php
<?php
spl_autoload_register( function($class) {
$parts = explode('\\', $class);
$path = $_SERVER['DOCUMENT_ROOT'] . 'Classes/';
require_once $path . end($parts) .'.php';
});
use Classes\Process;
use Classes\View;
$process = new Process();
$block = new View($process);
Better Option:
2. Leap years are years where an extra day is added to the end of
the shortest month,
February. How do you check if a year is a leap year or not?
INPUT: 2022
OUTPUT: Not a leap year
INPUT: 2020
OUTPUT: Leap year
Program:
PHP v7.4.30
Directories:
Classes
|_ Calendar.php
|_ ViewLeapYear.php
view
|_ template
|_ leap_year.phtml
index.php
process.php
Source:
Classes/Calendar.php
<?php
namespace Classes;
class Calendar
{
public function __construct() {}
/**
* @return $this
*/
public function execute() {
if(isset($_POST["year"])) {
if($this->checkIfLeapYear($_POST["year"])) {
$_SESSION['message'] = "{$_POST["year"]} is leap year";
} else {
$_SESSION['message'] = "{$_POST["year"]} is not leap year";
}
}
header('Location: index.php');
return $this;
}
/**
* @param $year
* @return bool
*/
protected function checkIfLeapYear($year) {
return cal_days_in_month(CAL_GREGORIAN,2,$year) == 29;
}
Classes/ViewLeapYear.php
<?php
namespace Classes;
class ViewLeapYear {
/**
* @var string
*/
protected $message;
/**
* @return $this
*/
public function render() {
$this->loadSessionMessage();
include('view/template/leap_year.phtml');
return $this;
}
/**
* @return void
*/
protected function loadSessionMessage() {
if(isset($_SESSION['message'])) {
$this->message = $_SESSION['message'];
}
}
/**
* @return string
*/
public function getMessage() {
return $this->message;
}
view/template/leap_year.phtml
<div class="form-wrap">
<form action="process.php" method="post" />
<div class="input-wrap">
<input type="number" name="year" class="year-input text-box" />
</div>
<br />
<div class="panel-wrap">
<button type="submit">Check If Leap Year</button>
</div>
</form>
<?php if($this->getMessage()): ?>
<br/>
<p><strong><?=$this->getMessage()?></strong></p>
<?php endif ?>
</div>
index.php
<?php
session_start();
spl_autoload_register( function($class) {
$parts = explode('\\', $class);
$path = $_SERVER['DOCUMENT_ROOT'] . 'Classes/';
require_once $path . end($parts) .'.php';
});
use Classes\ViewLeapYear;
$block = new ViewLeapYear();
session_unset();
process.php
<?php
session_start();
spl_autoload_register( function($class) {
$parts = explode('\\', $class);
$path = $_SERVER['DOCUMENT_ROOT'] . 'Classes/';
require_once $path . end($parts) .'.php';
});
use Classes\Calendar;
$calendar = new Calendar();
$calendar->execute();
3. Write a php program to loop over the json data. Suppose, you
have the following json
data.
[
{
"name" : "John Garg",
"age" : "15",
"school" : "Ahlcon Public school"
},
{
"name" : "Smith Soy",
"age" : "16",
"school" : "St. Marie school"
},
{
"name" : "Charle Rena",
"age" : "16",
"school" : "St. Columba school"
}
]
Program:
PHP v7.4.30
Directories:
Classes
|_ JsonClass.php
|_ JsonView.php
view
|_ template
|_ json_view.phtml
index.php
Source:
Classes/JsonClass.php
<?php
namespace Classes;
class JsonClass
{
/**
* @var string
*/
protected $data;
/**
* @var array[]
*/
protected $jsonLoaded;
/**
* @return $this
*/
public function execute() {
$this->loadJsonData();
return $this;
}
/**
* @return $this
*/
protected function loadData() {
$this->data = '[
{
"name" : "John Garg",
"age" : "15",
"school" : "Ahlcon Public school"
},
{
"name" : "Smith Soy",
"age" : "16",
"school" : "St. Marie school"
},
{
"name" : "Charle Rena",
"age" : "16",
"school" : "St. Columba school"
}
]
';
return $this;
}
/**
* @return $this
*/
protected function loadJsonData() {
$this->jsonLoaded = json_decode($this->data);
return $this;
}
/**
* @return array[]
*/
public function getLoadedJson() {
return $this->jsonLoaded;
}
}
Classes/JsonView.php
<?php
namespace Classes;
class JsonView {
/**
* @var JsonClass
*/
private $process;
/**
* @return $this
*/
public function render() {
$this->process->execute();
return $this;
}
/**
* @return array[]
*/
public function getValues() {
return $this->process->getLoadedJson();
}
}
view/template/json_view.phtml
index.php
<?php
spl_autoload_register( function($class) {
$parts = explode('\\', $class);
$path = $_SERVER['DOCUMENT_ROOT'] . 'Classes/';
require_once $path . end($parts) .'.php';
});
use Classes\JsonClass;
use Classes\JsonView;
$process = new JsonClass();
$block = new JsonView($process);
/**
* @param $value string
* @return array
*/
public function countLettersDigits($value) {
$lettersOnly = preg_replace ('/[^A-Za-z]/u', '', $value);
$digitsOnly = preg_replace ('/[^\d+]/u', '', $value);
return [
"LETTERS" => strlen($lettersOnly),
"DIGITS" => strlen($digitsOnly)
];
}
RUN EXAMPLE:
Function Source:
/**
* @var string
*/
protected $endString = "";
/**
* @var string
*/
protected $newString = "";
/**
* @param $value
* @return string
*/
protected function checkLastCharacter($value) {
$endString = substr(rtrim($value), -1);
switch($endString) {
case "!":
$this->newString = rtrim($value,"!");
$this->endString = "!".$this->endString;
$this->checkLastCharacter($this->newString);
break;
case "?":
$this->newString = rtrim($value,"?");
$this->endString = "?".$this->endString;
$this->checkLastCharacter($this->newString);
break;
default:
$this->newString = $value;
}
return $this->newString.$this->endString;
}
/**
* @param $value
* @return string
*/
public function trimQuestionExclamationMark($value) {
return $this->checkLastCharacter($value);
}
RUN:
Function Source:
/**
* @param array $values
* @param $percent
* @return array|float[]|int[]
*/
public function calculateArray(array $values, $percent = 25) {
$percentage = $percent/100;
$minValue = min($values);
$totalRemoved = 0;
$excluded = [];
foreach ($values as $key => $value) {
if($value != $minValue) {
$toRemove = $value*$percentage;
$totalRemoved = $totalRemoved+$toRemove;
$values[$key] = $value-$toRemove;
} else {
$excluded[] = $key;
}
}
return array_map(function ($v, $k) use ($minValue, $totalRemoved,
$excluded) {
return $v == $minValue && in_array($k,$excluded) ? $minValue+
$totalRemoved : $v;
}, $values, array_keys($values));
}
RUN EXAMPLE:
$values = [5,6,3,4,8,7];
var_dump(Class::calculateArray($values, 25));
Function Source:
/**
* @param $value string
* @return array
*/
public function arrayGroupClusters(string $value) {
$array = str_split(preg_replace ('/\s/u', '', $value));
$newSet = [];
foreach($array as $key=>$item) {
$checkValue = preg_grep('~'.$item.'~', $newSet);
if(!empty($checkValue)) {
foreach($checkValue as $k=>$value) {
$newSet[$k] = $value.$item;
}
} else {
$newSet[] = $item;
}
}
return $newSet;
}
RUN EXAMPLE:
MYSQL EXAM
MYSQL EXAM
1. Write a mysql statement to determine the age of each of the
students.
+----+--------------+------------+------------+
| id | name | department | birth |
+----+--------------+------------+------------+
| 1 | Maria Gloria | CS | 1994-03-12 |
| 2 | John Smith | IT | 1993-02-07 |
| 3 | Gal Rao | CS | 1992-09-11 |
| 4 | Jakey Smith | EC | 1990-08-31 |
| 5 | Rama Saho | IT | 1994-12-09 |
| 6 | Maria Gaga | EC | 1993-10-09 |
+----+--------------+------------+------------+
GIVEN:
Table Name = students
STATEMENT:
SELECT
`students`.`name`,
TIMESTAMPDIFF(year, `students`.`birth`, NOW()) as `age`
FROM `students`;
2. Write a mysql statement to get the names of students containing exactly four
characters.
+----+-------+---------+------------+
| id | name | dept_id | birth |
+----+-------+---------+------------+
| 1 | Maria | 2 | 1994-03-12 |
| 2 | John | 1 | 1993-02-07 |
| 3 | Gal | 4 | 1992-09-11 |
| 4 | Jakey | 2 | 1990-08-31 |
| 5 | Rama | 1 | 1994-12-09 |
| 6 | Maria | 4 | 1993-10-09 |
+----+-------+---------+------------+
GIVEN:
Table Name = students
STATEMENT:
SELECT
`students`.`name`
FROM `students `
WHERE CHAR_LENGTH(`students`.`name`) = 4;
Answer:
If the column is set to AUTO INCREMENT and reach its maximum
value, the process to generate the sequence number will fail and no
further data will be added (no rows can be inserted in the table).
Answer:
Answer:
MySQL query is not case sensitive. You can write it in lower cases,
upper cases, camel cases, or mix of mentioned cases.
Statement: