Problem when printing specific array data - php

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();

Related

PHP OOP only accessing first line of text file

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!

Values are not passing from HTML form into a PHP class

EDITED: Added checking stops into code.
keeping OOP design, what am I doing wrong?
The triangle sides are not passing into the classes properly.
I already tested the object with parameters inside the PHP file and it's working excellent. So it seems that the only culprit here is how I'm passing the params inside the classes.
Here is my shape.php:
<?php
abstract class Shape{
abstract protected function getArea();
abstract protected function getPerimeter();
}
class Triangle extends Shape{
private $_sides = array();
private $_perimeter = null;
public $status = 0;
function __construct($s0=0, $s1=0, $s2=0){
$this->_sides[] = $s0;
$this->_sides[] = $s1;
$this->_sides[] = $s2;
echo 'constructed<hr>';
//calculate perimeter:
$this->_perimeter = array_sum($this->_sides);
echo 'calculated perimeter<hr>';
$this->checkForm();
}
public function checkForm(){
if (!empty($_POST['submit'])){
$checkIt = $this->status = 1;
/* echo 'status is <hr>'.$checkIt;*/
}
return $this->status;
}
public function proceed(){
if ($this->status == 1){
echo 'proceed func started<hr>';
$this->_sides[0] = $_POST['s0'];
$this->_sides[1] = $_POST['s1'];
$this->_sides[2] = $_POST['s2'];
echo 'Side 1: '.$this->_sides[0] = $_POST['s0'].'<hr>';
echo 'Side 2: '.$this->_sides[1] = $_POST['s1'].'<hr>';
echo 'Side 3: '.$this->_sides[2] = $_POST['s2'].'<hr>';
}else{
echo 'This didn\'t work as planned... :(';
}
}
public function getArea(){
return (sqrt(
($this->_perimeter/2) *
(($this->_perimeter/2)- $this->_sides[0]) *
(($this->_perimeter/2)- $this->_sides[1]) *
(($this->_perimeter/2)- $this->_sides[2])
));
}
public function getPerimeter(){
return $this->_perimeter;
}
}
/*$check = new Triangle(2, 2, 2);*/
$check = new Triangle();
echo $check->proceed();
echo 'status is: '.$check->status.'<hr>';
echo 'The '.get_parent_class($check).' is a '.get_class($check).'. It\'s Perimeter is: '.$check->getPerimeter().'M.<br>';
echo 'The '.get_parent_class($check).' also has an area of: '.$check->getArea().'M.<br>';
And this is my index.php file:
<div class="row">
<div class="boxy">
<form method="post" action="Shape.php">
<label for="s0">Side 1</label>
<input name="s0" type="number" placeholder="Side 0"><br>
<label for="s1">Side 2</label>
<input name="s1" type="number" placeholder="Side 1"><br>
<label for="s2">Side 3</label>
<input name="s2" type="number" placeholder="Side 2"><br>
<input type="submit" name="submit" value="Run It.">
</form>
</div>
</div>
There are few issues with your code, such as:
You're trying to set up triangle properties in the constructor but you're not passing any values. See this statement,
$check = new Triangle();
You didn't make use of checkForm() and proceed() method.
Though there are several solutions to this problem, one would be like this:
Keep your constructor method empty, like this:
function __construct(){}
And change your proceed(), getArea() and getPerimeter() methods in the following way,
private function proceed(){
if ($this->status == 1){
$this->_sides[0] = isset($_POST['s0']) ? $_POST['s0'] : 0;
$this->_sides[1] = isset($_POST['s1']) ? $_POST['s1'] : 0;
$this->_sides[2] = isset($_POST['s2']) ? $_POST['s2'] : 0;
}else{
echo 'This didn\'t work as planned... :(';
}
}
public function getArea(){
if($this->checkForm()){
$this->proceed();
return (sqrt(
($this->_perimeter/2) *
(($this->_perimeter/2)- $this->_sides[0]) *
(($this->_perimeter/2)- $this->_sides[1]) *
(($this->_perimeter/2)- $this->_sides[2])
));
}else{
echo "Something went wrong. ";
}
}
public function getPerimeter(){
if($this->checkForm()){
$this->proceed();
return $this->_perimeter = array_sum($this->_sides);
}else{
echo "Something went wrong. ";
}
}
Well, I actually found the error, I forgot to return the proceed() results.
Here it is amended and fully working:
abstract class Shape{
abstract protected function getArea();
abstract protected function getPerimeter();
}
class Triangle extends Shape{
private $_sides = array();
private $_perimeter = null;
public $status = 0;
function __construct($s0=0, $s1=0, $s2=0){
$this->_sides[] = $s0;
$this->_sides[] = $s1;
$this->_sides[] = $s2;
echo 'constructed<hr>';
//calculate perimeter:
$this->_perimeter = array_sum($this->_sides);
echo 'calculated perimeter<hr>';
$this->checkForm();
}
public function checkForm(){
if (!empty($_POST['submit'])){
$checkIt = $this->status = 1;
/* echo 'status is <hr>'.$checkIt;*/
}
return $this->status;
}
public function proceed(){
if ($this->status == 1){
echo 'proceed func started<hr>';
$this->_sides[0] = $_POST['s0'];
$this->_sides[1] = $_POST['s1'];
$this->_sides[2] = $_POST['s2'];
echo 'Side 1: '.$this->_sides[0] = $_POST['s0'].'<hr>';
echo 'Side 2: '.$this->_sides[1] = $_POST['s1'].'<hr>';
echo 'Side 3: '.$this->_sides[2] = $_POST['s2'].'<hr>';
}else{
echo 'This didn\'t work as planned... :(';
}
return $this->_sides;
}
public function getArea(){
return (sqrt(
($this->_perimeter/2) *
(($this->_perimeter/2)- $this->_sides[0]) *
(($this->_perimeter/2)- $this->_sides[1]) *
(($this->_perimeter/2)- $this->_sides[2])
));
}
public function getPerimeter(){
return $this->_perimeter;
}
}
$check = new Triangle($_POST['s0'], $_POST['s1'], $_POST['s2']);
/*$check = new Triangle();*/
echo 'status is: '.$check->status.'<hr>';
echo 'The '.get_parent_class($check).' is a '.get_class($check).'. It\'s Perimeter is: '.$check->getPerimeter().'M.<br>';
echo 'The '.get_parent_class($check).' also has an area of: '.$check->getArea().'M.<br>';

OOP class private/protected

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;
}

the form does not print out the details

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
}
}
?>

php add multiple to cart method

I am currently able to add a quantity of a product by one or reduce it by one within my cart however I'm trying to add a method whereby I can submit a quantity that I input into a text field.
To increase by one, this is the main part of the code. It is found on the index page.
echo ' Plus 1';
This is the code on the cart page to get that uniquenum and action:
if (isset($_GET['increase1'])) {
$result = 'cart_' . $_GET['increase1'];
$_SESSION[$result] = isset($_SESSION[$result]) ? $_SESSION[$result] + 1 : 0;
}
How could I get the $uniquenum variable from the index page to the cart page using a form and post or get request. If I could do this I could update a quantity. Many thanks in advance.
I'd suggest you put all code belonging to the logic of the cart into a class of it's own. You can then use it as a facade in your code:
// initialize session for Cart
$_SESSION['cart'] || $_SESSION['cart'] = new Cart();
// fetch cart from session
$cart = $_SESSION['cart'];
Then provide methods by cart that offer the functionality you're looking for, either in a simplified form:
$cart->increadeByOne($item);
Or by giving full access to encapsulation of a more differentiated level:
$cart->getItem($item)->getQuantity()->increaseBy($number);
The last example might seem to be bloated, but generally it's good to have a base Cart class so you can better handle and test your operations.
You can then bind that with your GET request:
if (isset($_GET['increase1']))
{
$cart->getItem($_GET['increase1'])->getQuantity->increaseByOne();
}
Some rough Cart and Quantity layout:
Class CartItemQuantity
{
private $item;
private $quantity = 0;
public function __construct(CartItem $item)
{
$this->item = $item;
}
public function increaseByOne()
{
$this->increaseBy(1);
}
public function decreaseByOne()
{
$this->quantity = max(0, $this->quantity - 1);
}
public function increaseBy($number)
{
$this->quantity = max(0, $this->quantity + $number);
}
public function getQuantity()
{
return $this->quantity;
}
public function setQuantity($quantity)
{
if (is_string($quantity) && ctype_digit($quantity))
{
$quantity = (int) $quantity;
}
if (!is_int($quantity))
{
throw new InvalidArgumentException('Not a valid quantity (%s).', $quantity);
}
$this->quantity = max(0, $quantity);
}
}
Class CartItem
{
private $quantity;
...
public function __construct()
{
$this->quantity = new CartItemQuantity($this);
...
}
public function getQuantity()
{
return $this->quantity;
}
}
Class CartItems
{
...
/**
* #return CartItem
*/
public function getItem($item)
{
...
return $item;
}
}
Class Cart
{
/**
* #var CartItems
*/
private $items;
...
public function increaseByOne($item)
{
$this->items->getItem($item)->getQuantity()->increaseByOne();
}
/**
* #return CartItem
*/
public function getItem($item)
{
return $this->items->getItem($item);
}
}
// next line breaks for formatting only, take them out
echo '<form action="cart.php" method="get">
<input type="hidden" name="increasewhat" value="'.$uniquenum.'">
<label for="increaseby">Increase by</label>
<input type="text" name="increaseby" value="1">
<input type="submit" name="increaseyes" value="Yes!">
</form>';
//real linebreaks from here, parameters assumed to be validated
$result = 'cart_' . $_GET['increasewhat'];
$_SESSION[$result] = (isset($_SESSION[$result]) ? $_SESSION[$result]:0)+$_GET['increaseby'];
<form action='cart.php' method='GET'>
Input quantity:<br/>
<input type='text' name='increase1'><br/>
<input type='submit' value='Increase'/>
</form>
<form name="add_to_cart" method="get" action="cart.php">
<label for="uniquenum">Quantity: </label>
<input type="text" name="uniquenum" />
<input type="submit" value="Add to cart" />
</form>
On the server side:
if (isset($_GET['uniquenum'])) {
$uniquenum = $_GET['uniquenum'];
/* Important! Check if it is an integer */
if(is_int($uniquenum)) {
$_SESSION[$result] = isset($_SESSION[$result]) ? $_SESSION[$result] + $uniquenum : 0;
} else {
echo "Invalid input!";
}
}

Categories