I have created a form in html which takes all the information using the method post in php to print them out for the user but its seems like that I have a problem with my form. It does not print out the entered details by the user, I have tried to fill up and then press submit to create an object of the class profile assigning all the information from the user to the object and print them out on the browser but nothing appear on the browser.
I have also tried to echo the methods like getFirstName but its the same nothing comes up, can anyone help me to find out whats the problem with the code and how can I fix it.
Please note that I have included three different files one is the html form and the other one is the passingdata.php which will get all the information entered by the user and the third file is the class profile which is used in the passingdata to create an object and give it all the needed information in order to create an object of that class.
Finally, I have invoked the method printDeatils which should print out all the information entered by the user
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?php echo 'Student Deatils'; ?></title>
</head>
<body>
<p>Please enter your Details:</p>
<div>
<form name="student" method="post" action="passingdata.php">
<div>
<label>First name:</label> <input type ="text" name="first_name">
<label>Last name</label> <input type ="text" name="last_name">
<br></br>
<label>International student</label> <input type="checkbox" name="international">
<br></br>
<fieldset>
<legend>Course</legend>
<label>CS <input type="radio" name="course" value="CS"></label>
<label>SE <input type="radio" name="course" value="SE"></label>
<label>MIT <input type="radio" name="course" value="MIT"></label>
</fieldset>
<br></br>
<input type="submit" name="Submit" value="Submit">
<input type="reset" name="Resit" value="Reset">
</div>
</form>
</div>
<?php
?>
</body>
</html>
The passing data file:
<?php
require("profile.php");
$ss = new Profile($_POST['first_name'], $_POST["last_name"],
$_POST["course"], $_POST["international"]);
echo $ss->printDtails();
?>
The class profile:
<?php
class Profile {
private $_firstName, $_lastName, $_international, $_course;
function __contruct ($firstName, $lastName, $course, $international) {
$this->_firstName = $firstName;
$this->_lastName = $lastName;
$this->_course = $course;
$this->_international = $international;
}
public function setFirstName($firstName)
{
$this->_firstName = $firstName;
}
public function setLastName($lastName)
{
$this->_lastName = $lastName;
}
public function setInternational($inter)
{
$this->_international = $inter;
}
public function setCourse($course)
{
$this->_course = $course;
}
public function getFirstName()
{
return $this->_firstName;
}
public function getLastName()
{
return $this->_lastName;
}
public function getInternational()
{
return $this->_international;
}
public function getCourse()
{
return $this->_course;
}
public function printDtails()
{
echo "$_firstName";
}
}
?>
In the printDtails() function you need to echo $this->_firstName
Also in your class, the word construct is spelled wrong, you have __contruct it needs to be __construct
This worked for me, however I did modify your code slightly.
I must admit that I'm learning classes myself, so this may or may not be what you're looking for, however it did work.
Also, inside your printDtails() function, it needed a echo $this->_firstName; etc.
I changed your constructs to $this->_firstName = $_POST['first_name']; etc.
N.B.: The word construct was mispelled as contruct with the missing s
Here is what I came up with:
<?php
class Profile {
private $_firstName, $_lastName, $_international, $_course;
function __construct ($_firstName, $_lastName, $_international, $_course)
{
$this->_firstName = $_POST['first_name']; // modified
$this->_lastName = $_POST['last_name']; // modified
$this->_course = $_POST['course']; // modified
$this->_international = $_POST['international']; // modified
}
public function setFirstName($firstName)
{
$this->_firstName = $firstName;
}
public function setLastName($lastName)
{
$this->_lastName = $lastName;
}
public function setInternational($inter)
{
$this->_international = $inter;
}
public function setCourse($course)
{
$this->_course = $course;
}
public function getFirstName()
{
return $this->_firstName;
}
public function getLastName()
{
return $this->_lastName;
}
public function getInternational()
{
return $this->_international;
}
public function getCourse()
{
return $this->_course;
}
public function printDtails()
{
echo $this->_firstName . "\n"; // modified
echo $this->_lastName . "\n"; // modified
echo $this->_course . "\n"; // modified
echo $this->_international . "\n"; // modified
}
}
?>
Related
I'm working with a player class, the code prints a form with name, lastname and location fields that have to be filled in to add a new player.
But I have a problem when printing the players since I only print the names of the players, when I try to print the data separately (name, lastname and location) I do not print anything.
session_start();
class Player {
private $players;
private $name;
private $lastname;
private $location;
public function __construct($name,$lastname,$location)
{
$this->name = $name;
$this->lastname = $lastname;
$this->location = $location;
$this->players = array();
}
public function getName()
{
return $this->name;
}
public function getLastname()
{
return $this->lastname;
}
public function getLocation()
{
return $this->location;
}
public function addPlayer($onePlayer)
{
$this->players[] = $onePlayer;
return $this;
}
public function printPlayers()
{
foreach($this->players as $player){
// just show the name¿?.
echo $player.'<br />';
// The problem is here.
/*echo $player['name'].'<br />';
echo $player['lastname'].'<br />';
echo $player['location'].'<br />';*/
}
}
public function __toString()
{
return $this->name;
return $this->lastname;
return $this->location;
}
}
function printForm()
{
echo '<FORM METHOD="POST" style="text-align: center; margin-top: 73px;">
<h2>Add Players</h2>
<label>Add the name : </label><INPUT class="form" TYPE = "text" NAME = "name"> <br>
<label>Add the lastname : </label><INPUT class="form" TYPE = "text" NAME = "lastname"> <br>
<label>Add the location : </label><INPUT class="form" TYPE = "text" NAME = "location"> <br><br>
<INPUT class="form" TYPE = "submit" VALUE = "add" name="action">
<INPUT class="form" TYPE = "submit" VALUE = "list" name="action">
</ FORM>';
}
// Load the player data of the session and if it does not exist create a new player.
function loadData()
{
return isset($_SESSION['player']) ? $_SESSION['player'] : new Player();
}
// Save the player's data in the session.
function saveData($player)
{
$_SESSION['player'] = $player;
}
printForm();
$player = loadData();
if(isset($_POST['action']))
{
switch($_POST['action'])
{
case 'add':
$player->addPlayer(new Player($_POST['name'],$_POST['lastname'],$_POST['location']));
saveData($player);
break;
case 'list':
echo '<hr />';
$player->printPlayers();
break;
}
}
It looks like in the problematic part you're trying to access private properties using array syntax. That won't work for a couple of reasons
The properties aren't accessible there because they're defined as private
You can't get them with array syntax. If they weren't private you'd need to use $player->name.
But fortunately you have also written some getters, so you should be able to use those instead, like this:
echo $player->getName();
I am doing an assignment for school, and I am having an odd problem. The object that I have created only accesses the first line of a text file we are using. This is highly problematic for me because if I build a database and can only use the first line, well, so much for usefulness.
My instructor and I both can't figure out why this problem is here, and we have worked on this for over a week.
Here is the text file:
003345, Pauline, Sampson, Admin, 14.96
012345, Mike, King, Manager, 20.47
123456, Pete, Smith, Accountant, 25.53
345678, Mary, Jones, Accountant, 32.53
456789, Mary, King, Manager, 18.35
777999, Caroline, Baxter, Nurse, 27.45
Here is my start HTML:
<!DOCTYPE html>
<html>
<head>
<title>Modify1.html</title>
<link rel ="stylesheet" type="text/css" href="sample.css" />
</head>
<body>
<h1>Weekly Pay report</h1>
<form action="modify1.php" method="post">
<table>
<tr><td>Employee ID 1</td><td><input type="text" name="id1"></td></tr>
<tr><td>Employee ID 2</td><td><input type="text" name="id2"></td></tr>
<tr><td>Employee ID 3</td><td><input type="text" name="id3"></td></tr>
</table>
<p><input type = "submit" value = "Submit">
</form>
</body>
</html>
Here is my PHP output:
<!DOCTYPE html>
<html>
<head>
<title>Modify 1</title>
<link rel ="stylesheet" type="text/css" href="sample.css" />
</head>
<body>
<?php
include("inc-employee-object.php");
$id1 = $_POST["id1"];
$id2 = $_POST["id2"];
$id3 = $_POST["id3"];
$emp1 = new Employee();
$emp2 = new Employee();
$emp3 = new Employee();
$emp1->findEmployee($id1);
$emp2->findEmployee($id2);
$emp3->findEmployee($id3);
print ("<p>Weekly Pay for ".$emp1->getFirstName()." ". $emp1->getLastName().": $".$emp1->getWeeklyPay()."</p>");
print ("<p>Weekly Pay for ".$emp2->getFirstName()." ". $emp2->getLastName().": $".$emp2->getWeeklyPay()."</p>");
print ("<p>Weekly Pay for ".$emp3->getFirstName()." ". $emp3->getLastName().": $".$emp3->getWeeklyPay()."</p>");
?>
</body>
</html>
And here is my object:
<?php
class Employee
{
private $empID;
private $firstName;
private $lastName;
private $jobTitle;
private $hourlyWage;
public function addEmployee()
{
$empRecord = $this->empID.",
".$this->firstName.",
".$this->lastName.",
".$this->jobTitle.",
".$this->hourlyWage."\n";
$empFile = fopen("employees.txt", "a");
fputs($empFile, $empRecord);
fclose($empFile);
}
public function findEmployee($id)
{
$empFile = fopen("employees.txt", "r");
$empRecord = fgets($empFile);
$notFound = true;
while (!feof($empFile) and $notFound)
{
list ($empID, $fName, $lName, $title, $wage) = explode(",", $empRecord);
if ($id == $empID)
{
$this->empID = $empID;
$this->firstName = $fName;
$this->lastName = $lName;
$this->jobTitle = $title;
$this->hourlyWage = $wage;
$notFound = false;
}
if ($notFound == false)
{
return 1;
}
else
{
return 0;
}
$empRecord = fgets($empFile);
}
fclose($empFile);
}
public function getID()
{
return $this->empID;
}
public function setID($empID)
{
$this->empID = $empID;
}
public function getFirstName()
{
return $this->firstName;
}
public function setFirstName($fName)
{
$this->firstName = $fName;
}
public function getLastName()
{
return $this->lastName;
}
public function setLastName($lName)
{
$this->lastName = $lName;
}
public function getJobTitle()
{
return $this->jobTitle;
}
public function setJobTitle($title)
{
$this->jobTitle = $title;
}
public function getHourlyWage()
{
return $this->hourlyWage;
}
public function setHourlyWage($hourlyWage)
{
$this->hourlyWage = $hourlyWage;
}
public function getWeeklyPay()
{
$this->hourlyWage = trim($this->hourlyWage);
return number_format ($this->hourlyWage * 40, 2);
}
public function getAnnualPay()
{
$this->hourlyWage = trim($this->hourlyWage);
return number_format($this->hourlyWage * 40 *52,2);
}
} // end of class definition
?>
Can anyone tell me what I'm doing wrong?
Thanks
In your while loop, you will always exit on the first item due to this code...
if ($notFound == false)
{
return 1;
}
else
{
return 0;
}
Under any condition, this will exit out of the loop and function. This should be outside the loop and probably at the end of the function.
If you want to stop the loop once the record is found, then use break; something like...
if ($id == $empID)
{
$this->empID = $empID;
$this->firstName = $fName;
$this->lastName = $lName;
$this->jobTitle = $title;
$this->hourlyWage = $wage;
$notFound = false;
break; // Exit loop
}
#NigelRen is right about the loop exiting once a condition is found. But that may be by your design and should not matter in this case as you are calling the class separately for each id.
If you look at the your text file you are missing commas in between the wage and the employee id's. So it is only seeing the first row and not the others.
Cheers!
I want to display the number of the table, which I get from the HTML form, in this method: private function getComanda();.
I use public function displayMethod() to call the private function getComanda().
I want the table number to be displayed in the class Table, in the public function setMasa($nr_masa), which has a switch. It is not displaying anything at all.
When I try to display the table number with this function from Shop class, public function getProperty(), it works. I am stuck, can anyone help?
I tried to make the function getProperty() as both private and protected and it did not show any results, but if I change it to public it does.
This is the HTML code:
<html>
<body>
<form action="" method="post">
<p>Preturi:</p><br/>
Nr-Masa: <input type="text" name="nr_masa" /><br/>
<input type="submit" value="Trimite" name="submit_masa" />
</form>
</body>
</html>
The class shop where:
$nr_masa=number of table; $_masa1=table1
class Shop
{
protected $nr_masa;
private $_masa1;
public function setComanda($nr_masa)
{
$this->_nr_masa = $nr_masa;
}
public function displayMethod()
{
$this->_masa1=$this->getComanda();
print $this->_masa1;
}
private function getComanda()
{
return "<br /><br />Table number:" . $this -> _nr_masa . "<br />";
}
public function getProperty()
{
return $this -> _nr_masa . "<br />";
}
}
class Table extends Shop
{
public function setMasa($nr_masa)
{
switch($nr_masa) {
case "1";
echo "Masa Nr.1 a fost rezervata";
echo $this -> displayMethod();
break;
case "2";
echo "Masa Nr.2 a fost rezervata";
echo $this -> displayMethod();;
break;
case "3";
echo "Masa Nr.3 a fost rezervata";
echo $this -> displayMethod();
break;
case "4";
echo "Masa Nr.4 a fost rezervata";
echo $this -> displayMethod();
break;
default:
echo "Masa nu exista";
}
}
}
$TabelData = new Table;
$ShopData = new Shop;
if (isset($_POST['submit_masa'])) {
$nr_masa = $_POST["nr_masa"];
$TabelData -> setMasa($nr_masa);
$ShopData -> setcomanda($nr_masa);
}
you are using print in function displayMethod() and then using echo in function setMasa
public function displayMethod()
{
$this->_masa1=$this->getComanda();
return $this->_masa1; <-- replace print with return;
}
I have a Class to manage the users and everything was working fine until I had to add more columns to the table and modify 2 names. Now one of the modified names, the function that returns the column content is not working, the colum is fill with data but it's not printing anything when I call the function.
I rechecked many times the code, looking for a bad typed name or something, but everything seems to be fine, I can't find the problem...
This is my class:
require_once('aet.php');
class staff {
private $aet;
private $not_working_column;
private $working_column;
public function __construct() {
$this->aet = new aet();
}
private function generate($staff) {
$this->not_working_column = $staff->not_working_column;
$this->working_column = $staff->working_column;
}
private function addInformation($stmt) {
$i = 0;
$stmt->bind_result($not_working_column, $working_column);
while ($stmt->fetch()) {
$arrayStaff[$i] = new staff();
$arrayStaff[$i]->setNotWorkingColum($not_working_column);
$arrayStaff[$i]->setWorkingColumn($working_column);
$i++;
}
}
public function StaffFromEmail($email) {
$mysqli = $this->aet->getAetSql();
if ($stmt = $mysqli->prepare("SELECT * FROM staff WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0) {
$exit = false;
}
else {
$arrayStaff = $this->addInformation($stmt);
$this->generate($arrayStaff[0]);
$exit = true;
}
}
return $exit;
}
public function setNotWorkingColum($not_working_column) {
$this->not_working_column = $not_working_column;
}
public function getNotWorkingColum() {
return $this->not_working_column;
}
public function setWorkingColumn($working_column) {
$this->working_column = $working_column;
}
public function getWorkingColumn() {
return $this->working_column;
}
}
And in the form where users can update their info
<div class="item">
<div class="input">
<input type="text" placeholder="" name="staff_info[]" value="<?php echo $staff->getNotWorkingColum(); ?>" />
</div>
</div>
<div class="item">
<div class="input">
<input type="text" placeholder="" name="staff_info[]" value="<?php echo $staff->getWorkingColumn(); ?>" />
</div>
</div>
I've also made a video https://www.youtube.com/watch?v=9S_Uw7IK_xY
My fault, while changing the name of a column I missed one:
public function setPersonalPhone($personal_phone) {
$this->phone = $personal_phone;
}
Should be:
public function setPersonalPhone($personal_phone) {
$this->personal_phone = $personal_phone;
}
I am trying to create object oriented login system.
I've started to improve my OOP skills, by solving some rather easier issues, when building a website. So it started with a login system, I have followed a tutorial on youtube, that helped me made a Login class, but as it went on, it raised many doubts (The code is 100 lines so I'll pass on pasting it).
When I execute the code without entering value then the output is invalid form submission not return invalid username/password etc.
When I enter the wrong username and password then return invalid form submission;
It should not run properly...
Please help me
I enter my code here.
<?php
class Login
{
private $_id;
private $_username;
private $_password;
private $_passmd5;
private $_errors;
private $_access;
private $_login;
private $_token;
//create a function
public function __construct()
{
$this->_errors = array();
$this->_login = isset($_POST['login'])?1:0;
$this->_access = 0;
$this->_token = $_POST['token'];
$this->_id = 0;
$this->_username= ($this->_login)? $this->filter($_POST['username']):$_SESSION['username'];
$this->_password= ($this->_login)? $this->filter($_POST['password']): '';
$this->_passmd5 = ($this->_login)? md5($this->_password) : $_SESSION['password'];
}
public function IsLoggedIn()
{
($this->_login)? $this->VerifyPost() : $this->VerifySession();
return $this->_access;
}
public function filter($var)
{
return preg_replace('/[^a-zA-Z0-9]/','',$var);
}
public function VerifyPost()
{
try
{
if($this->IsTokenValid())
throw new Exception('Invalid Form Submission');
if($this->IsDataValid())
throw new Exception('Invalid Form Data');
if($this->VerifyDatabase())
throw new Exception('Invalid Username / Password');
$this->_access=1;
$this->RegisterSession();
}
catch(Exception $e)
{
$this->_errors[]= $e->getMessage();
}
}
public function VerifySession()
{
if($this->SessionExist() && $this->VerifyDatabase())
{
$this->_access=1;
}
}
public function VerifyDatabase()
{
include "db_connection.php";
$q="select 'user_id' from user where username='".$this->_username."' and password='".$this->_passmd5."'";
echo $q;
$result=mysql_query($q);
if(mysql_num_rows($result))
{
// list($this->_id)= #array_values(mysql_fetch_assoc($result));
$row=mysql_fetch_array($result);
$this->_id= $row['user_id'];
return true;
}
else
{
return false;
}
}
public function IsDataValid()
{
return preg_match('/^[a-zA-Z0-9]{5,12}$/',$this->_username) && preg_match('/^[a-zA-Z0-9]{5,12}$/',$this->_password)?1:0;
}
public function IsTokenValid()
{
return (!isset($_SESSION['token']) || $this->_token != $_SESSION['token'])?0:1;
}
public function RegisterSession()
{
$_SESSION['user_id']=$this->_id;
$_SESSION['username']=$this->_username;
$_SESSION['password']=$this->_passmd5;
}
public function SessionExist()
{
return (isset($_SESSION['username']) && isset($_SESSION['password']))? 1:0;
}
public function ShowErrors()
{
echo '<h3> Errors: </h3>';
foreach($this->_errors as $key=>$value)
{
echo $value .'<br>';
}
}
}
?>
I handle this code in my login form i.e
enter code here
<?php
session_start();
if(isset($_POST['login']))
{
include "login.php";
$login =new Login();
if($login->IsloggedIn())
{
echo "success";
//header("location:index.php");
}
else
{
$login->ShowErrors();
}
}
$token=$_SESSION['token']= md5(uniqid(mt_rand(),true));
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form name="login_form" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<p>
<label for="username">Username</label>
<input type="text" name="username" />
<br />
<label for="password">Pssword</label>
<input type="password" name="password" />
<br />
<input type="hidden" name="token" value="<?=$token;?>">
<input type="submit" name="login" value="Login" />
</p>
</form>
</body>
</html>
the problem is in token check
try to hide token validation exception by commenting the line:
throw new Exception('Invalid Form Submission');
and run the code