Can't get values from textbox to class - php

I want to make a basic calculator. Every thing is set, the textboxes and buttons. It needs to be OOP, but that gives me problems. It worked before until I tried to do it in OOP.
I don't get errors but when ever I try to let the code calculate a sum, it results the answer as 0. Its probably because the class doesn't get the values from the textboxes, but I don't know how to fix it.
Code of the class where the calculation needs to be:
class CountUp
{
public static $_sum;
public static $number1;
public static $number2;
public function __construct()
{
self::$_sum;
self::$number1;
self::$number2;
}
public function getnumber1()
{
self::$number1 = ($_POST['number1']);
return self::$number1;
}
public function getnumber2()
{
self::$number2 = ($_POST['number2']);
return self::$number2;
}
public static function getsum()
{
$_sum = self::$number1 + self::$number2;
return $_sum;
}
}
Sorry if this is a stupid question, I'm bad at php.
EDIT: This is where the values are supossed the come from:
<html>
<head>
</head>
<body>
<form name ="btw calculate" method="post" action="test2.php"><br/>
enter a number <br/>
<input type="tekst" name="number1" value=""><br/>
<input type="submit" name="plus" value="+">
<input type="submit" name="retract" value="- "><br/>
<input type="submit" name="divide" value="/ ">
<input type="submit" name="multiply" value="* "><br/>
enter a second number <br/>
<input type="tekst" name="number2" value=""><br/>
</form>
</body>
</html>
EDIT2: I'm an idiot, forgot to add this part to this question:
<?php
include("plus.class.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['plus']))
{
echo CountUp::getSum();
}
else
{
//still empty for now
}
}
?>

You are mixing up static functions which are related to the class definition.
And object instance functions, which are related to each 'new' 'instance' of a class you create.
Here in an input form and the class adding the $_POST array values together.
<?php if (!empty($_POST['number1'])) {
// object instance version
class CountUp
{
private $number1 = 0;
private $number2 = 0;
public function setNumber1($number)
{
$this->number1 = $number;
}
public function setNumber2($number)
{
$this->number2 = ($number)
public function getSum()
{
$_sum = $this->number1 + $this->number2;
return $_sum;
}
}
$addTwoNumbers1 = new CountUp();
$addTwoNumbers1->setNumber1($_POST['number1']);
$addTwoNumbers1->setNumber2($_POST['number2']);
?>
<p> The answer of: <?= $_POST['number1']?> + <?= $_POST['number2'] ?> = <?= $addTwoNumbers1->getSum(); ?>
<?php
}
?>
<html>
<head>
</head>
<body>
<form name ="btw calculate" method="post" action=""><br/>
enter a number <br/>
<input type="text" name="number1" value=""><br/>
<p>will be added to...</p>
enter a second number <br/>
<input type="text" name="number2" value=""><br/>
<input type="submit" name="plus" value="add the two numbers together...">
</form>
</body>
</html>

Related

PHP not executing after try block

I have created a demo calculator which works perfect except one time when the form gets submitted it goes inside try block and the rest html page doesn't get displayed.. am i doing it wrong? i dont see any reason why it shouldn't execute the rest of the code
I very well understand the try catch finally concept but cant see where's the error
this is my class.calculator.php
class NoNumberProvided_Exception extends Exception {}
class Calculator {
function __construct() {
$args = func_get_args();
if(!$args) {
throw new NoNumberProvided_Exception("Please provide atleast 2 numbers");
} else {
if($args[0] && $args[1]) {
if($args[2] == "Add") {
echo $args[0]+$args[1];
} else if($args[2] == "Divide") {
echo $args[0]/$args[1];
} else if($args[2] == "Subtract") {
echo $args[0]-$args[1];
} else if($args[2] == "Multiply") {
echo $args[0]*$args[1];
}
} else {
throw new NoNumberProvided_Exception("Please provide atleast 2 numbers");
}
}
}
}
PHP:
if(isset($_POST['submit'])) {
include 'class.calculator.php';
try {
$num = new Calculator($_POST['number1'], $_POST['number2'], $_POST['submit']);
echo $num; // after the form gets submitted, this gets echoed but the html form below doesnt show on the page
} catch (NoNumberProvided_Exception $nonumber) {
echo $nonumber->getMessage();
}
}
HTML:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Number1: <input type="text" name="number1" id="number1" />
<br/>
Number2: <input type="text" name="number2" id="number2" />
<br/><br/>
<input type="submit" id="submit" name="submit" value="Add" />
<input type="submit" id="submit" name="submit" value="Divide" />
<input type="submit" id="submit" name="submit" value="Subtract" />
<input type="submit" id="submit" name="submit" value="Multiply" />
</form>
The reason you are not seeing the HTML content after echo $num is because you are getting a fatal error.
This is seen when running your code in a php console (php -a)
php > $num = new Calculator(1,2,'Subtract');
-1
php > echo $num;
PHP Catchable fatal error: Object of class Calculator could not be converted to string in php shell code on line 1
PHP Stack trace:
PHP 1. {main}() php shell code:0
php >
To address this problem, we could make a few conceptual changes to your Calculator class:
A method should only do One Thing. A constructor is best used for initialization, and your calculator's functions Add, Subtract, Multiply, and Divide probably should be separate methods.
As a general rule, an object (being a part of the model, or logic section), should never echo or print its result. This is, in my opinion, a merging of logic and presentation-- which you should strive to separate. It's also part of the problem you ran into.
My first inclination would be to pass the parameters into the methods, instead of the constructor. This allows you to type hint the values you expect. I'm showing integer as example. If bad data (string) is passed, it will throw an exception. If only 1 value is passed, it will throw an exception.
At the end of the day, there's no one "right" way to do it; experience helps show ways that will be easier to work on later. :)
My suggestions, FWIW...
Class:
<?php
class Calculator {
public function __construct() { }
public function add(int $addend1, int $addend2) {
return $addend1 + $addend2;
}
public function subtract(int $subtrahend, int $minuend) {
return $subtrahend - $minuend;
}
public function multiply(int $factor1, int $factor2) {
return $factor1 * $factor2;
}
public function divide(int $dividend, int $divisor) {
return $dividend / $divisor;
}
}
PHP / HTML
function assignPostVar($name) {
if(isset($_POST[$name])) {
return $_POST[$name];
}
}
$error = '';
if(isset($_POST['submit'])) {
$calc = new Calculator;
$n1 = assignPostVar('number1');
$n2 = assignPostVar('number2');
try {
switch($_POST['submit']) {
case 'Add':
$result = $calc->add($n1,$n2);
break;
case 'Subtract':
$result = $calc->subtract($n1,$n2);
break;
case 'Multiply':
$result = $calc->multiply($n1,$n2);
break;
case 'Divide':
$result = $calc->divide($n1,$n2);
break;
default:
throw new Exception('Invalid operation');
}
} catch (Exception $e) {
$error = $e->getMessage();
}
}
?>
<?php if($error): ?>
<div class="error">Encountered error: <?= $error ?></div>
<?php endif; ?>
<form method="POST">
Number1: <input type="text" name="number1" id="number1" />
<br/>
Number2: <input type="text" name="number2" id="number2" />
<br/><br/>
<input type="submit" id="add" name="submit" value="Add" />
<input type="submit" id="divide" name="submit" value="Divide" />
<input type="submit" id="subtract" name="submit" value="Subtract" />
<input type="submit" id="multiply" name="submit" value="Multiply" />
</form>

Undefined variable error in view even after passing the data from controller

I am trying to create a simple calculator that will perform calculation by unitary method
Below is my controller
class Calculator extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->helper('url');
}
public function index()
{
$mid_cal = 0;
$total_cost = 0;
$this->load->view('Calculator',$total_cost,$mid_cal);
//print_r($total_cost);
}
public function calculate()
{
//print_r($_POST);
$qty_purchased = $this->input->post('qty_purchased');
$item_cost = $this->input->post('item_cost');
$mid_cal = $item_cost / $qty_purchased;
$qty_used = $this->input->post('qty_used');
$total_cost = $mid_cal * $qty_used ;
$this->load->view('Calculator',$total_cost,$mid_cal);
//$this->load->view('calculator');
}
}
Below is my view
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html>
<body>
<form action="<?php echo base_url(); ?>index.php/calculator/calculate" method='post'>
Item:<br>
<input type="text" name="item" >
<br>
Qty Purchased:<br>
<input type="text" name="qty_purchased" >
<br>
Cost of Item:<br>
<input type="text" name="item_cost" >
<br>
Mid Cal:<br>
<input type="text" name="mid_cal" value="<?php echo $mid_cal ?>">
<br>
Qty Used:<br>
<input type="text" name="qty_used" >
<br>
Total Cost:<br>
<input type="text" name="total_cost" value="<?php echo $total_cost ?>">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I am getting undefined variable error in view for $total_cost and $mid_cal. I am sending the data in the calculate function. I also tried sending blank data in my index function. I am not sure how to solve this issue. Any help will be most welcome. Thanks in advance.
In your controller.
Replace Index Method/Function with below and try.
public function index()
{
$data['mid_cal'] = 0;
$data['total_cost'] = 0;
$this->load->view('calculator',$data);
//print_r($total_cost);
}
You have to pass an array in controller to the view as like above and now you can access directly using $total_cost and $mid_cal.

How do i clear this array by user input in php/html?

I am working on a program that has the user type in their course, first name, last name, and description of a program. The code is mostly done except for getting the clear the array button to work. When I use the unset array to clear the array on its own, it works but then the user cant enter in more data. I want to have the user be able to clear the data. Here is my code:
<?php
session_start();
?>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "gethint.php?q="+str, true);
xmlhttp.send();
}
}
</script>
<?php
function clear(){ //this is the problem
unset($_SESSION['courses']);
return true;
}
?>
</head>
<body>
<form method="POST">
Course: <input type="text" name="courses" />
<br /><br />
First Name: <input type="text" name="firstname" />
<br /><br />
Last Name: <input type="text" name="lastname" />
<br /><br />
Description: <input type="text" name="description" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<?php
// First we check if the form has been sent and we have a value
if (!empty($_POST['courses'])) {
if (!isset($_SESSION['courses']))
$_SESSION['courses'] = array(); // Initialize the array if it doesn't exist
// Add the value to our array
$_SESSION['courses'][] = array("course" => $_POST['courses'],
"firstname" => $_POST['firstname'],
"lastname" => $_POST['lastname'],
"description" => $_POST['description']);
}
// If there are values to show, print them!
if (!empty($_SESSION['courses'])) {
foreach ($_SESSION['courses'] as $course) {
echo $course['course']." ".
$course['firstname']." ".
$course['lastname']." ".
$course['description']." ".
"<br />";
}
}
?>
<input type="submit" name="Clear" value="Clear" onclick="clear()"> //this is the problem
<?php
?>
</body>
</html>
Can someone please help?
<?php
// there is nothing wrong with this function.
function clear() {
unset($_SESSION['courses']);
return true;
}
?>
Okay, this function is fine, there is nothing wrong with it. But, you can't use this function like:
<input type="submit" name="Clear" onclick="Clear()" /> <!-- this is the problem -->
You see that onclick="Clear()", and that php function clear()? Yeah, you can't execute php functions with a html onclick="". You can only do that with javascript functions.
But you can do something like this:
<?php
if(isset($_POST['Clear']))
{
// if the user submits the form, then the following code will be executed.
clear();
}
?>
<input type="submit" name="Clear" value="Clear" onclick="clear()">
clear() would be calling a javascript function. You have correctly written a php function.
Check the value of the submit button "Clear" to be "clear" and if true run the PHP function clear().
if ($_POST['Clear'] === 'clear') {
clear();
}

PHP My code doesn't send to the right page after using edit button

I have the following problem. I created a .php file that creates(extends) two new pages. In the first page there is a button called submit which after click on it send me to the next page called editname. When I made click on the button (edit)of the second page, it send me to the third page called recorndname. In the third page, there are two buttons called update and delete which send me to the second page. But, actually it is working as it should. Here is part of my code.
//here is my main class
class main {
public function __construct() {
$page_request = 'homepage';
if(isset($_REQUEST['page'])) {
$page_request = $_REQUEST['page'];
}
$page = new $page_request;
if($_SERVER['REQUEST_METHOD'] == 'GET') {
$page->get();
} elseif ($_SERVER['REQUEST_METHOD'] == 'POST'){
$page->post();
} else{
$page->delete();
}
}
}
Here is my page class. In this part seems neither one of the functions are called.
//Page class
class page {
public function get() {
echo 'I am a get method page';
}
public function post() {
echo 'I am a post method';
$user=new users();
//$user->addUser($_POST["firstname"],$_POST["lastname"],$_POST["email"]);
if($_POST['botton'] == 'Submit'){
$user->addUser($_POST["firstname"],$_POST["lastname"],$_POST["email"]);
} else if($_POST['botton'] == 'Update'){
$user->update($_POST["email"],$_POST["firstname"],$_POST["lastname"]);
} else if($_POST['botton'] == 'Delete'){
$user->deleteUser($_POST["email"]);
}
}
public function delete(){
echo 'I am a delete method';
}
}
Here are my extended pages.
//Page classes
class homepage extends page {
public function get() {
echo 'homepage';
echo'<form action="projectBackup.php?page=editname" method="post">
First name:<br>
<input type="text" name="firstname" value="">
<br>
Last name:<br>
<input type="text" name="lastname" value="">
<br>
Email Address:<br>
<input type="text" name="email" value="">
<br><br>
<input type="submit" name="button" value="Submit">
</form>';
}
}
class editname extends page {
public function post(){
echo 'editname';
$users=new users();
$userlist=$users->listUsers();
echo '<table><tr><th>First Name</th><th>Last Name</th><th>Email Address</th></tr>';
foreach($userlist as $Kuser=>$user){
echo '<tr><td>'.$user['fname'].'</td><td>'.$user['lname'].'</td><td>'.$Kuser.'</td><td>';
echo '<form action="projectBackup.php?page=recordname" method="get">
<input type="hidden" name="email" value="$Kuser">
<input type="submit" value="Edit"></form>';
}
echo '</table>';
}
}
class recordname extends page {
public function get() {
echo 'recordname';
$users=new users();
$userlist=$users->listUsers();
echo'<form action="projectBackup.php?page=editname" method="post">
First name:<br>
<input type="text" name="firstname" value="$userlist[$_GET["email"]["fname"]">
<br>
Last name:<br>
<input type="text name="lastname" value="$userlist[$_GET["email"]["lname"]">
<br>
Email Address:<br>
<input type="text" name="email" value="$_GET["email"]">
<br><br>
<input type="submit" name="button" value="Update">
<input type="submit" name="button" value="Delete">
</form>';
}
}
Can someone help me with this? Thank you in advance.

how to call php function from submit button?

my filename is contacts.php that have two submit buttons;i want that if insert button is pressed insert function is called and if select is pressed select is called.i have written following code:
//contacts.php
<?php
if(isset($_REQUEST['select']))
{
select();
}
else
{
insert();
}
?>
<html>
<body>
<form action="contacts.php">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select()
{
//do something
}
function insert()
{
//do something
}
?>
but it is not working .please help
<?php
if (isset($_REQUEST['insert'])) {
insert();
} elseif (isset($_REQUEST['select'])) {
select();
}
Your code is calling insert() even if no button is clicked, which will happen when the page is first displayed.
use post method because it is secure
//contacts.php
<?php
if(isset($_POST['select']))
{
select();
}
else
{
insert();
}
?>
<html>
<body>
<form action="contacts.php" method="post">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select()
{
//do something
}
function insert()
{
//do something
}
?>
If you are using return inside function to return the result , you have to use echo to print the result while calling function.
if(isset($_REQUEST['select']))
{
echo select();
}
elseif(isset($_REQUEST['insert']))
{
echo insert();
}
As has been described by several people (summarizing the previous comments), you have two options.
The first is to send the data via POST or GET to the server directly and reserve (refresh) the page based on whatever you do inside select() and insert().
While this is not the right place for a POST v GET discussion, convention is to use POST when sending data to the server. POST is slightly more secure because the information is not stored in the browser. Read more about the two here: http://www.w3schools.com/tags/ref_httpmethods.asp
The second option is to use AJAX to accomplish your task without refreshing the web page. In short, AJAX uses Javascript methods that you place on your page to communicate with your server, thus avoiding the need for the PHP on the server to actually change anything on the page (which would require a refresh). A code example of AJAX can be found here: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
<?php
$insert = $_POST['insert'];
$select = $_POST['select'];
if ($insert) {
insert();
}
if ($select) {
select();
}
else {
echo 'press any button...';
}
?>
<html>
<body>
<form action="contacts.php" method="post">
<input type="text" name="txt"/>
<input type="submit" name="insert" value="insert" />
<input type="submit" name="select" value="select"/>
</form>
<?php
function select() {
echo 'you pressed the [select] button';
exit;
}
function insert() {
echo 'you pressed the [insert] button';
exit;
}
?>

Categories