PHP PDO lab
Reorganize the code (refactor), write a separate class that implements the interface StudentInterface and use the methods in this class to show the list of students and details of a student.
- All SQL queries are moved into the methods defined in the interface and the methods return data back to the calling program.
- Use prepared statements for queries that take one or more input parameters.
interface StudentInterface {
public function visAlle() : array;
public function visStudent(int $id) : Student;
}
- visAlle () returns the array of references to Student objects .
- visStudent (int $ id) returns the student object with the specified id.
Student.class.php
<?php
class student {
private $id;
private $etternavn;
private $fornavn;
private $klasse;
private $mobil;
private $www;
private $epost;
private $klassenavn;
function __construct() { }
function hentId() {
return $this->id;
}
function hentNavn() {
return $this->fornavn . " " . $this->etternavn;
}
function hentEtterNavn() {
return $this->etternavn;
}
function hentForNavn() {
return $this->fornavn;
}
function hentMobil() {
return $this->mobil;
}
function hentURL() {
return $this->www;
}
function hentKlasse() {
return $this->klasse;
}
function hentEpost() {
return $this->epost;
}
function hentKlasseNavn() {
return $this->klassenavn;
}
//Setters
function settForNavn($fornavn) {
$this->fornavn = $fornavn;
}
function settEtterNavn($etterNavn) {
$this->etternavn = $etterNavn;
}
function settMobil($mobil) {
$this->mobil = $mobil;
}
function settURL($www) {
$this->www = $www;
}
function settKlasse($klasse) {
$this->klasse = $klasse;
}
function settEpost($epost) {
$this->epost = $epost;
}
}
?>
StudentRegister.class.php
<?php
class StudentRegister implements StudentInterface
{
private $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function visAlle(): array
{
$studenter= array();
try
{
// implement this
}
catch (Exception $e) {
print $e->getMessage() . PHP_EOL;
}
return $studenter;
}
public function visStudent(int $id) : Student
{
try
{
// implement this
}
catch (InvalidArgumentException $e) {
print $e->getMessage() . PHP_EOL;
}
}
}
StudentInterface.class.php
<?php
interface StudentInterface {
public function visAlle() : array;
public function visStudent(int $id) : Student;
}
db4.php
<?php
spl_autoload_register(function ($class_name) {
require_once $class_name . '.class.php';
});
require_once 'auth_pdo.php';
$studReg = new StudentRegister($db);
if(isset($_GET['id']) && ctype_digit($_GET['id']))
{
$id = intval($_GET['id']);
if($student = $studReg->visStudent($id)) {
print("Navn: " . $student->hentNavn() . "<br />\n");
print("Klasse: ". $student->hentKlasseNavn() . "<br />\n");
print("Mobil: " . $student->hentMobil() . "<br />\n");
print("Epost: ". $student->hentEpost() . "<br />\n");
}
else {
// Ingen poster
echo "Beklager, fant ingen poster!";
}
}
else {
print("Studenter:<br />");
$studenter = $studReg->visAlle();
foreach ($studenter as $student )
{
print("<a href=" . $_SERVER['PHP_SELF'] . "?id=" . $student->hentId() . ">". $student->hentNavn() . "</a><br/>\n");
}
}
?>
auto_pdo.php
<?php
$host = "www.host.com";
$dbname = "database";
$username = "brukernavn";
$password = "passord";
try
{
$db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
}
catch(PDOException $e)
{
//throw new Exception($e->getMessage(), $e->getCode);
print($e->getMessage());
}
?>Answer:
Program:
Student.class.php
<?php
class student {
private $id;
private $etternavn;
private $fornavn;
private $klasse;
private $mobil;
private $www;
private $epost;
function __construct() { }
function hentId() {
return
$this->id;
}
function hentNavn() {
return $this->fornavn
. " " . $this->etternavn;
}
function hentMobil() {
return
$this->mobil;
}
function hentKlasseNavn() {
return
$this->klasse;
}
function hentEpost() {
return
$this->epost;
}
function hentUrl() {
return$this->www;
}
function hentEtternavn() {
return
$this->etternavn;
}
function hentFornavn(){
return
$this->fornavn;
}
public function setId($id)
{
$this->id =
$id;
}
public function
setEtternavn($etternavn)
{
$this->etternavn =
$etternavn;
}
public function setFornavn($fornavn)
{
$this->fornavn =
$fornavn;
}
public function setKlasse($klasse)
{
$this->klasse =
$klasse;
}
public function setMobil($mobil)
{
$this->mobil =
$mobil;
}
public function setWww($www)
{
$this->www =
$www;
}
public function setEpost($epost)
{
$this->epost =
$epost;
}
}
StudentInterface.class.php
<?php
interface StudentInterface
{
public function visAlle() : array;
public function visStudent(int $id ) :
student;
public function leggTilStudent(student $student)
: int;
public function updateStudent(int $id);
public function visKlasse() : array;
// public function visKlasseMatte() :
array;
}
StudentRegister.class.php
<?php
class StudentRegister implements StudentInterface
{
private $db;
public function __construct(PDO $db)
{
$this->db =
$db;
}
public function visAlle(): array
{
$studenter= array();
try
{
$result = $this->db->query("SELECT * FROM `studenter` ORDER
BY `studenter`.`etternavn` ASC");
while ($student = $result->fetchObject('Student')) {
$studenter[] = $student;
}
}
catch (Exception $e)
{
print $e->getMessage() . PHP_EOL;
}
return
$studenter;
}
public function visStudent(int $id) :
Student
{
try
{
$stmt = $this->db->prepare("SELECT etternavn, fornavn, mobil,
www, epost FROM studenter WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
if(!$student = $stmt->fetchObject('Student')) {
throw new InvalidArgumentException('No student with id: ' .
$id);
}
else
return $student;
}
catch
(InvalidArgumentException $e) {
print $e->getMessage() . PHP_EOL;
}
return $student;
}
public function leggTilStudent(student $student)
: int
{
$etternavn =
htmlentities($_GET['etternavn']);
$fornavn =
htmlentities($_GET['fornavn']);
$klasse =
htmlentities($_GET['klasse']);
$mobil =
htmlentities($_GET['mobil']);
$www =
htmlentities($_GET['www']);
$epost =
htmlentities($_GET['epost']);
try {
$stmt = $this->db->prepare("INSERT INTO `studenter` (`id`,
`etternavn`, `fornavn`, `klasse`, `mobil`, `www`, `epost`,
`opprettet`) VALUES (NULL, :etternavn, :fornavn, :klasse, :mobil,
:www, :epost, CURRENT_TIMESTAMP)");
$stmt->bindParam(':etternavn', $etternavn);
$stmt->bindParam(':fornavn', $fornavn);
$stmt->bindParam(':klasse', $klasse);
$stmt->bindParam(':mobil', $mobil);
$stmt->bindParam(':www', $www);
$stmt->bindParam(':epost', $epost);
$stmt->execute();
$id = $this->db->lastInsertId();
} catch (PDOException
$e) {
echo "Error: " . $e->getMessage();
}
return $id;
}
public function updateStudent(int $id)
{
$etternavn =
htmlentities($_GET['etternavn']);
$fornavn =
htmlentities($_GET['fornavn']);
$klasse =
htmlentities($_GET['klasse']);
$mobil =
htmlentities($_GET['mobil']);
$www =
htmlentities($_GET['www']);
$epost =
htmlentities($_GET['epost']);
try {
$stmt = $this->db->prepare("UPDATE studenter SET fornavn=
:fornavn, etternavn= :etternavn, klasse= :klasse, mobil= :mobil,
www= :www, epost= :epost WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->bindParam(':etternavn', $etternavn);
$stmt->bindParam(':fornavn', $fornavn);
$stmt->bindParam(':klasse', $klasse);
$stmt->bindParam(':mobil', $mobil);
$stmt->bindParam(':www', $www);
$stmt->bindParam(':epost', $epost);
$stmt->execute();
}
catch (PDOException
$e){
echo "Error: " . $e->getMessage();
}
}
public function visKlasse() : array
{
$klassenavn =
htmlentities($_GET['klasse']);
$studenter =
array();
try {
$stmt = $this->db->prepare("SELECT * FROM `studenter` INNER
JOIN klasse on studenter.klasse = klasse.id WHERE klasse.klassenavn
= :klassenavn ORDER BY `studenter`.`etternavn` ASC");
$stmt->bindParam(':klassenavn', $klassenavn);
$stmt->execute();
while ($student = $stmt->fetchObject('Student')) {
$studenter[] = $student;
}
}
catch (Exception
$e){
print $e->getMessage() . PHP_EOL;
}
return $studenter;
}
}
StudentRegister.php
<?php
include "../tpl/template.php";
function __autoload($class_name) {
require_once $class_name . '.class.php';
}
require_once '../auth/auth.php';
$studReg = new StudentRegister($db);
if(isset($_GET['id']) && ctype_digit($_GET['id']))
{
$id = intval($_GET['id']);
if($student = $studReg->visStudent($id))
{
print("<br/>");
print("<a>");
print("Navn:".
htmlentities($student->hentNavn()) . "<br/>\n");
print("Klasse: ".
htmlentities($student->hentKlasseNavn()) . "<br
/>\n");
print("Mobil:
" . htmlentities($student->hentMobil()) . "<br
/>\n");
print("Epost: ".
htmlentities($student->hentEpost()) . "<br />\n");
print("</a>");
print("<br/>");
}
else {
echo "Beklager, fant
ingen poster!";
}
}
else{
print("<h1>Studenter:</h1><br
/>");
$studenter = $studReg->visAlle();
foreach ($studenter as $student )
{
print("<a href=" .
$_SERVER['PHP_SELF'] . "?id=" . $student->hentId() . ">".
$student->hentNavn() . "</a><br/>\n");
}
}
?>
<html>
<form action="" method="get">
<b>
<br>
Velg hvilken klasse du vil se:
<br>
</b>
<select
name="klasse">
<option value="">Velg tilhorighet</option>
<option value="2sta" id="2sta">2STA</option>
<option value="1stb" id="1stb">1STB</option>
</select>
<br>
<br>
<input type="submit"
name="btn_class" value="submit">
</form>
</html>
<?php
if(isset($_GET['btn_class'])){
$val = $_GET['klasse'];
print("<br>");
$studenter = $studReg->visKlasse();
foreach ($studenter as $student) {
print("<a href=" .
$_SERVER['PHP_SELF'] . "?id=" . $student->hentId() . ">".
$student->hentNavn() . "</a><br/>\n");
}
}
addStudent.php
<?php
include "../tpl/template.php";
function __autoload($class_name) {
require_once $class_name . '.class.php';
}
require_once '../auth/auth.php';
$studReg = new StudentRegister($db);
$student = new student();
if(isset($_GET['btn_add'])) {
try {
$nyStudent = $studReg->leggTilStudent($student);
$student->setEtternavn('etternavn');
$student->setFornavn('fornavn');
$student->setKlasse('klasse');
$student->setMobil('mobil');
$student->setWww('www');
$student->setEpost('epost');
print("<br>");
print("<a>");
echo "Ny student lagt
til!";
print("<br>");
print("</a>");
} catch (PDOException $e) {
echo "Error: " .
$e->getMessage();
}
}
?>
<html>
<form action="" method="get">
<p>
<label
for="lastname">
Etternavn:
<br>
<input id="etternavn" type="text" name="etternavn">
</label>
</p>
<p>
<label
for="firstname">
Fornavn:
<br>
<input id="fornavn" type="text" name="fornavn">
</label>
</p>
<p>
<label
for="class">
Klasse:
<br>
<input id="klasse" type="text" name="klasse">
</label>
</p>
<p>
<label
for="mobile">
Mobil:
<br>
<input id="mobil" type="text" name="mobil">
</label>
</p>
<p>
<label
for="homepage">
www:
<br>
<input id="www" type="text" name="www">
</label>
</p>
<p>
<label
for="mail">
epost:
<br>
<input id="epost" type="text" name="epost">
</label>
</p>
<p>
<button type="submit"
name = "btn_add">Legg til student</button>
</p>
</form>
</html>
updateStudent.php
<?php
include "../tpl/template.php";
function __autoload($class_name) {
require_once $class_name . '.class.php';
}
require_once '../auth/auth.php';
$studReg = new StudentRegister($db);
$student = new student();
$studenter = $studReg->visAlle();
foreach ($studenter as $student )
{
print("<a href=" . $_SERVER['PHP_SELF'] .
"?id=" . $student->hentId() . ">". $student->hentNavn() .
"</a><br/>\n");
if(isset($_GET['id'])){
$id =
intval($_GET['id']);
if($student =
$studReg->visStudent($id)){
}
}
}
if(isset($_GET['btn_update'])) {
try {
$nyStudent =
$studReg->updateStudent($student->hentId());
print("<br>");
print("<a>");
echo "Student
Oppdatert!";
print("<br>");
print("</a>");
} catch (PDOException $e) {
print("<br>");
print("<a>");
echo "Error: " .
$e->getMessage();
print("<br>");
print("</a>");
}
}
$etternavn = htmlentities($student->hentEtternavn());
$fornavn = htmlentities($student->hentFornavn());
$klasse = htmlentities($student->hentKlasseNavn());
$mobil = htmlentities($student->hentMobil());
$www = htmlentities($student->hentUrl());
$epost = htmlentities($student->hentEpost());
?>
<html>
<form action="" method="get">
<p>
<label
for="lastname">
Etternavn:
<br>
<input id="etternavn" type="text" name="etternavn"
value="<?=$etternavn?>">
</label>
</p>
<p>
<label
for="firstname">
Fornavn:
<br>
<input id="fornavn" type="text" name="fornavn"
value="<?=$fornavn?>">
</label>
</p>
<p>
<label
for="class">
Klasse:
<br>
<input id="klasse" type="text" name="klasse"
value="<?=$klasse?>">
<select name="klasse">
<option value="">Velg tilhorighet</option>
<option value="2sta" id="2sta">2STA</option>
<option value="1stb" id="1stb">1STB</option>
</select>
</label>
</p>
<p>
<label
for="mobile">
Mobil:
<br>
<input id="mobil" type="text" name="mobil"
value="<?=$mobil?>">
</label>
</p>
<p>
<label
for="homepage">
www:
<br>
<input id="www" type="text" name="www"
value="<?=$www?>">
</label>
</p>
<p>
<label
for="mail">
epost:
<br>
<input id="epost" type="text" name="epost"
value="<?=$epost?>">
</label>
</p>
<p>
<button type="submit"
name = "btn_update">Oppdater informasjon</button>
</p>
</form>
</html>.
PHP PDO lab Reorganize the code (refactor), write a separate class that implements the interface StudentInterface...
I don't know why my script is receiving so many errors class DB { private$dbHost="localhost"; private $dbUsername="sixfoour"; private $dbPassword="499e9n3"; private $dbName="sleep"; public $db_con; public function _construct() { if(!isset($this->db) { try { $pdo = new PDO("mysql:host=".$this->dbHost.",;dbname=".$this-dbName", $this->dbUsername,$this->dbPassword); $this->dbPassword; $this->setAttribute(PDO::ATTR,PDO::ERROMODE_EXECEPTION); $this->db_con=$pdo; } catch(PDOEXECEPTION $e) { die("Failed to connect with mySQL": $e->getMessage()); } } } public function login($user_name, $user_password) { $stmt= $this->db _con->prepare("SELECT * FROM Login_Info WHERE user_name=:user_name"); $stmt->execute(array(":user_name"=>$user_name)); $row=$stmt->fetch(PDO::FETCH_ASSOC); $count=$stmt->rowCount(); if($row['user_password']==$user_password) { return $count; } else { return false; } } public...
How can I print the Database table in PHP please ? here I have form for name and email, also I have php code that allow user to add his name and email to my database, all I need to print my final database when the user click on submit. <form action="" method="post"> <label>Name :</label> <input type="text" name="name" required="required" placeholder="Please Enter Name"/><br /><br /> <label>Email :</label> <input type="email" name="email" required="required" /><br/><br /> <input type="submit" value=" Submit " name="submit"/><br /> </form>...
Here is the code from the previous three steps:
#include <iostream>
using namespace std;
class Student
{
private:
//class variables
int ID;
string firstName,lastName;
public:
Student(int ID,string firstName,string lastName)
//constructor
{
this->ID=ID;
this->firstName=firstName;
this->lastName=lastName;
}
int getID() //getter method
{
return ID;
}
virtual string getType() = 0; //pure virtual function
virtual void printInfo() //virtual function to print basic details
of a student
{
cout << "Student type: " << getType() <<
endl;
cout << "Student ID: " << ID...
need source code for NetBeans
here is the file
Write a class PrimeSequence that implements the Sequence interface of Worked Example 10.1* and produces a sequence of prime numbers. * See Files section bj6_ch10_we.pdf Hint: Pseudocode to produce next prime: class Prime Sequence implements Sequence instance variable int p function next ()I isPrime-true While (isPrime) increment p; for (d-2; until d*d > p divides p) isPrime-false; d+) if (d if isPrime) return p; isPrime-true Use your PrimeSequence class to generate...
Question: Write the Main class code for the following application. The first three classes are given below. Lottery This lottery app allows users to sign up for an account, choose a random number or two, and then win a certain amount of money if their chosen number matches the number that the game draws. The house keeps the cash proceeds if nobody wins. The app must repeatedly do the following: Allow the user to (1) Add Player Account (2) Play...
Given the Interface Code write a java class that implements this interface and show the working functionality in the main method: public interface CustomList<T> { /** * This method should add a new item into the <code>CustomList</code> and should * return <code>true</code> if it was successfully able to insert an item. * @param item the item to be added to the <code>CustomList</code> * @return <code>true</code> if item was successfully added, <code>false</code> if the item was not successfully added (note: it...
USE JAVA: Given the Interface Code and the Interface Implementation Code; Write Junit Tests to test all fuctionality. ------------- Interface code: public interface CustomList { /** * This method should add a new item into the CustomList and should * return true if it was successfully able to insert an item. * @param item the item to be added to the CustomList * @return true if item was successfully added, false if the item was not successfully added (note: it...
PHP - Use of classes This is a further development of the previous task, the participant registration. You must use the following Participant class. <?php class Deltaker { private $etterNavn; private $forNavn; private $fAar; function __construct(string $fornavn, string $etternavn, string $aar) { $this->forNavn = $fornavn; $this->etterNavn = $etternavn; $this->fAar = $aar; } function hentEtterNavn() : string { return $this->etterNavn; } function hentForNavn() : string { return $this->forNavn; } function hentFAar() : string{ return $this->fAar; } //Setters function settForNavn(string $fornavn) {...
In a file named LLBag.java, write a class called LLBag that implements the Bag interface using a linked list instead of an array. You may use a linked list with or without a dummy head node. Bag interface code: /* * Bag.java * * Computer Science 112, Boston University */ /* * An interface for a Bag ADT. */ public interface Bag { /* * adds the specified item to the Bag. Returns true on success * and...
In the Employee class, add an implementation for the calculatePension() method declared in the interface. Calculate the pension to date as the equivalent of a monthly salary for every year in service. 4) Print the calculated pension for all employees. ************** I added the interface and I implemented the interface with Employee class but, I don't know how can i call the method in main class ************ import java.io.*; public class ManagerTest { public static void main(String[] args) { InputStreamReader...