php: how to change array value (text) - php

I'm trying to change value in my array but can't for some reason...
`
My code:
<form action="index.php" method="POST" class="form-control">
<label for="soortMeel">Soort meel:</label>
<input type="text" name="soortMeel" id="soortMeel">
<label for="vorm">Soort vorm:</label>
<input type="text" name="vorm" id="vorm">
<label for="gewicht">gewicht:</label>
<input type="number" name="gewicht" id="gewicht">
<label for="gewicht">row aanpassen:</label>
<input type="number" name="arr_input" id="arr_input">
<div>
<input type="submit" name="add" value="add">
<input type="submit" name="update" value="update">
</div>
</form>
<?php
class brood {
public $soort_meel;
public $vorm_brood;
public $gewicht;
function __construct($soort_meel, $vorm_brood, $gewicht) {
$this->soort_meel = $soort_meel;
$this->vorm_brood = $vorm_brood;
$this->gewicht = $gewicht;
}
function getGewicht() {
return $this->gewicht;
}
function setGewicht($gewicht) {
$this->gewicht = $gewicht;
}
function getVorm_brood() {
return $this->vorm_brood;
}
function setVorm_brood($vorm_brood) {
$this->vorm_brood = $vorm_brood;
}
function getSoort_meel() {
return $this->soort_meel;
}
function setSoort_meel($soort_meel) {
$this->soort_meel = $soort_meel;
}
}
$soort_meel = isset($_POST['soortMeel']) && !empty($_POST['soortMeel']) ? $_POST['soortMeel'] : null;
$vorm_brood = isset($_POST['vorm']) && !empty($_POST['vorm']) ? $_POST['vorm'] : null;
$gewicht = isset($_POST['gewicht']) && !empty($_POST['gewicht']) ? $_POST['gewicht'] : null;
$arr_input = isset($_POST['update']) && !empty($_POST['update']) ? $_POST['update'] : null;
// if(isset($_SESSION['update'])) {
// $arr_input = $_SESSION['update'];
// } else {
// $brood_winkel['soort_meel'] = $soort_meel;
// }
if(isset($_SESSION['brood_winkel'])) {
$brood_winkel = $_SESSION['brood_winkel'];
} else {
$brood_winkel = array(
new brood("volkorenmeel", "volkorenbrood", "35 gram")
);
}
// ADD NEW BROOD
if ($soort_meel != null && $vorm_brood != null && $gewicht != null) {
array_push($brood_winkel, new brood($soort_meel, $vorm_brood, $gewicht));
}
foreach($brood_winkel as $newbrood) {
echo "<table>";
echo "<tr>";
echo "<th>" . $newbrood->getSoort_meel() . "</th>";
echo "<th>" . $newbrood->getVorm_brood() . "</th>";
echo "<th>" . $newbrood->getGewicht() . "</th>";
echo "</tr>";
echo "</table>";
}
$_SESSION['brood_winkel'] = $brood_winkel;
$_SESSION['update'] = $arr_input;
echo $brood_winkel[0];
?>
</body>
</html>
`
trying to echo array but doesn't work:
echo $brood_winkel[0];
Fatal error: Uncaught Error: Cannot use object of type brood as array
in index.php on line 148
Error: Cannot use object of type brood as array in
index.php on line 148
All i want is to set new value in the targetted index of the array.
(if something is not good explained ask them please).

As the error-message already mentions, you can't print a complete object or array with echo. For these cases always use print_r or var_dump.
var_dump($brood_winkel[0]);
print_r($brood_winkel[0]);
You can use echo, if you want to print out single values. In your case this could be one or multiple attribute values:
echo $brood_winkel[0]->getGewicht();
Also, I wanted to add that since all your object-attributes are public you actually don't need your getter-Functions. You can simply access them like this:
echo $brood_winkel[0]->gewicht;
This is also the same way how you can update single values of this object:
$brood_winkel[0]->gewicht = 2;
Of course you can also replace the complete object at the index of that array:
$test_brood = new brood("meel", "brood", "40");
$brood_winkel[0] = $test_brood;
I hope I could help you. Keep it up!

Related

Error code "Invalid argument supplied for foreach()" when using json_encode (oop, php)

I'm trying to create a to do list. When creating new posts it should encode the information to json and put the information in a json array. But somehow it seems the information isn't encoded correctly and when trying to print the posts I get the error message "Invalid argument supplied for foreach()". I just can't find where the mistake is.
I'm fairly new at this so to complex answers might be to hard for me to understand.
Edit:
Adding the whole freaking code. Something is seriously wrong. 🤦‍♀️
index:
<?php
spl_autoload_register(function ($class) {
include $class . '.class.php';
});
$allPosts = new Lista;
if(isset($_REQUEST['addNewPost'])){
$allPosts->addNewPost($_REQUEST['ett'], $_REQUEST['tva'], $_REQUEST['tre']);
}
?>
<?php $page_title = "Att göra lista";
include("includes/header.php");
?>
<?php
include("includes/sidebar.php");
?>
<h2>Min att göra lista</h2>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Uppgift: <input type="text" name="ett"/><br/>
Utfarare: <input type="text" name="tva"/><br/>
Senast: <input type="text" name="tre"/><br/>
<input type="submit" name="addNewPost" value="Lägg till post"/>
</form>
<?php
//Loopa igenom array
foreach ($allPosts->getTheList() as $key=>$val) {
echo "<section id='postPart'>" . $val->getEtt() . "<br/>" . $val->getTva(). " " . $val->getTre(). "</section><section id='buttonPart'><button type='button' name='klar'>Avklarad!</button> <button type='button' name='deletePost'>Ta bort</button>\n";
}
//echo "<section id='postPart'>" . $_REQUEST['one'] . "<br/>" . $_REQUEST['two'] . " " . $_REQUEST['three'] . "</section><section id='buttonPart'><button type='button' name='klar'>Avklarad!</button> <button type='button' name='deletePost'>Ta bort</button>\n";
var_dump($allPosts);
?>
</body>
</html>
Class: Lista:
<?php
class Lista{
public $theList=[];
function __construct(){
if(file_exists("text.json")>0)
$this->theList = json_decode(file_get_contents('text.json'), true);
}
function addNewPost($ett, $tva, $tre){
$posten = new Post ($ett, $tva, $tre);
array_push ($this->theList, $posten);
$jsonStr = json_encode($this->theList);
file_put_contents("text.json", $jsonStr);
}
function getTheList( ){
return $this->theList;
}
}
Class Post:
<?php
class Post{
public $ett;
public $tva;
public $tre;
function __construct ($ett, $tva, $tre){
$this->ett = $ett;
$this->tva = $tva;
$this->tre = $tre;
}
function getEtt():string{
return $this->ett;
}
function getTva(){
return $this->tva;
}
function getTre(){
return $this->tre;
}
}
Besides the typo, to json_encode an array of objects your need to make an exporter method which returns an array of each property or implement JsonSerializable
<?php
class Post implements JsonSerializable {
protected $whatIs = ' ';
protected $whoIs = ' ';
protected $whenIs = ' ';
function __construct($what,$who,$when){
$this->whatIs=$what;
$this->whoIs=$who;
$this->whenIs=$when;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
$arr = [];
$arr[] = new Post(1,2,3);
echo json_encode($arr);
Result:
[{"whatIs":1,"whoIs":2,"whenIs":3}]
I think your problem is on this line:
$jsonStr = json_encode($this->$thePost, JSON_PRETTY_PRINT);
You might be trying to do this :
$jsonStr = json_encode($thePost, JSON_PRETTY_PRINT);
Since $thePost is an object, and not a property of your class. It could work if $thePost is a string that match a property name.

how to validate and limit dynamic radio button inside a while loop

I tried to generate radio buttons dynamically from my database, but I am stuck where I need to limit (check if the user selected at least 5 groups(5 different games) of the generated button before submission into the database.
<?php while($row = mysql_fetch_array($query)) : ?>
<?php
$home_team = $row\['home_team'\];
$away_team = $row\['away_team'\];
$game_id = $row\['game_id'\];
$team_joined = $home_team.' VS '.$away_team;
$teams = $home_team.'vs'.$away_team;
$match_day = #$row\['match_day'\];
$match_time = #$row\['match_time'\];
date_default_timezone_set('Africa/Lagos');
$time = date('l, jS F h:iA');
?>
<?php
if (isset($_POST\['submit'\])) {
$amount = mysql_real_escape_string($_POST\['amount'\]);
$games = #$_POST\[''.$game_id.''\];
$countGames = count($games);
echo $countGames;
/* if ($countGames < 3) {
$errorfill = "please selecet 3 games";
} else { */
if ($amount) {
foreach ($games as $game) {
$gameValue = $game;
if ($amount < $bank_verify) {
$money_left = $bank_verify - $amount;
$deduct_query = mysql_query("UPDATE bank SET money_unit='$money_left' WHERE username='$username' ");
$query_start_game = mysql_query("INSERT INTO bet10_players VALUES('', '$username', '$amount',
'$gameValue', '$team_joined', '$game_id','$time', '$pin', '$match_day', '$match_time')") or die(mysql_error());
header("Location: print.php?pin=$pin&time=$time");
} else {
$errorbank = "SORRY!!! You do not have enough units to stake this bet";
}
}
} else {
$errorfill = "You have not entered any amount";
}
//}
}
?>
<form role="form" action="#" method="post">
<h5><?php echo $team_joined; ?></h5>
<h5><?php echo '<span style="color:#f0ad4e;">' . $match_day . ', ' . $match_time . '</span>'; ?></h5>
<label><input type="radio" name="<?php echo '' . $game_id . '\[' . $game_id . '\]'; ?>" value="<?php echo $home_team; ?>">Home</label>
<label><input type="radio" name="<?php echo '' . $game_id . '\[' . $game_id . '\]'; ?>" value="Draw ">Draw</label>
<label><input type="radio" name="<?php echo '' . $game_id . '\[' . $game_id . '\]'; ?>" value="<?php echo $away_team; ?>">Away</label>
<hr>
<?php endwhile; ?>
<div class="form-group">
<input type="text" name="amount" class="form-control" placeholder="Enter your amount here">
<input type="submit" name="submit" value="submit" class="btn btn-danger" style="margin-bottom: 10px;">
This is the link to the image of what I intend to achieve with these code https://i.stack.imgur.com/Xif8M.png
Because there are a lot of issues just with what you have, I can not actually "fix" what you have in good conscience. The mysql_* library is deprecated (removed in >= PHP7) and you are escaping a bunch of things you don't need to, as I noted. Also, as noted, using # to silence warnings is not a good idea, you will want to just fix them. If I were to do this, I would have a series of classes that I would create. I would also do an .htaccess or web.config (Windows) to force everything through the index page, but I suspect from your script you have individual pages, so I will go on that notion:
First off, I would probably create a base app that had some simple, helpful features.
/vendors/App.php
<?php
class App
{
# Easily return post values even if they don't exist without drawing errors
public function getPost($key=false)
{
if(!empty($key))
return (isset($_POST[$key]))? $_POST[$key] : false;
return $_POST;
}
# Easily return session values even if they don't exist without drawing errors
public function getSession($key=false)
{
if(!empty($key))
return (isset($_SESSION[$key]))? $_SESSION[$key] : false;
return $_SESSION;
}
# Used to render pages
public function render($file)
{
ob_start();
include($file);
$data = ob_get_contents();
ob_end_clean();
return $data;
}
}
/vendors/Game.php
If you create a base Game class, you will better be able to control Game-related base features
<?php
class Game extends App
{
protected $games = array();
protected $errors = array();
protected $con;
# Inject the database
public function __construct(\PDO $con)
{
$this->con = $con;
}
# Fetch a list (or just one) game
public function gameList($game_id = false)
{
$where = (!empty($game_id))? " WHERE game_id = '{$game_id}'" : "";
$this->games = array();
$query = $this->con->query("SELECT * FROM games{$where}");
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$this->games[] = $result;
}
return $this;
}
# Send back the games if stored
public function getGames($first = false)
{
# If you you only need one row returned
if($first)
return (isset($this->games[0]))? $this->games[0] : false;
# Return entire list
return $this->games;
}
# Count how many are currently stored
public function getCount()
{
return count($this->games);
}
}
/vendors/Game/Observer.php
If you create a base Game Observer class, you will better be able to control listeners and processing of requests.
<?php
namespace Game;
class Observer extends \Game
{
protected $time;
# This is a general listener method, listens for the post
# It needs work, I don't know where you are getting some of these
# variables from...I am injecting for example-sake
public function listen($bank_verify,$pin,$min=5)
{
# Listen for the submission
if(empty($this->getPost('submit')))
return $this;
elseif(empty($this->getSession('username')))
return $this;
# Fetch the post values, fitler empty
$REQUEST = array_filter($this->getPost('game'));
# See if there are at least 5 submitted
if(count($REQUEST) < $min) {
$this->errors[] = 'You must have at least '.$min.' selected';
return $this;
}
foreach($REQUEST as $id => $value) {
$this->games[$id] = $value;
}
$username = $this->getSession('username');
$amount = $this->getPost('amount');
if($amount < $bank_verify) {
$money_left = $bank_verify - $amount;
$this->updateAccount($money_left,$username);
foreach($this->games as $id => $value) {
$query_start_game = $this->con->prepare("INSERT INTO bet10_players VALUES('',?,?,?,?,?,?,?,?,?)");
$query_start_game->execute(array(
$username,
$amount,
$gameValue,
$team_joined,
$game_id,
$time,
$pin,
$match_day,
$match_time
));
}
}
else {
$this->errors[] = 'Not enough money.';
return $this;
}
header("Location: print.php?pin=$pin&time=$time");
exit;
}
# This sets the timezone (just once)
public function setTime($tz = 'Africa/Lagos')
{
date_default_timezone_set($tz);
$this->time = date('l, jS F h:iA');
return $this;
}
# This will update the account safely
public function updateAccount($money_left,$username)
{
$sql = "UPDATE bank SET money_unit = ? WHERE username = ?";
$query = $this->con->prepare($sql);
$query->execute(array($money_left,$username));
return $query;
}
# This probably needs work, but you should insert using this method
public function addBets($array,$table='bet10_players')
{
$fill = "'', ".implode(', ',array_fill(0,count($array),'?'));
$sql = "INSERT INTO `{$table}` VALUES({$fill})";
$query = $this->con->prepare($sql);
$query->execute($array);
return $query;
}
# Returns the time if need be...
public function getTime()
{
return $this->time;
}
}
/config.php
I would create this page to be included on all pages at the top. It can be expanded and is good to keep everything consistent like your root path and such.
<?php
# start the session
session_start();
# Create some useful defines
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('CLASSES',ROOT_DIR.DS.'vendors');
define('DB_HOST','localhost');
define('DB_NAME','databasename');
define('DB_USER','root');
define('DB_PASS','');
# Create a class autoloader which turns a \Namespace\Class into a directory
# like /var/html/domain/mydomain/vendor/Namespace/Class.php
spl_autoload_register(function($class) {
$path = str_replace(DS.DS,DS,CLASSES.DS.str_replace('\\',DS,$class).'.php');
if(is_file($path))
include_once($path);
});
/index.php
<?php
# Check if we are inside the class, if not, do so
if(!isset($this)) {
# Include the config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Create your connection (you should expand on this...)
$con = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_PASS);
# Create a Game object
echo (new \Game\Observer($con))->render(__FILE__);
# Stop further execution
exit;
}
# Now we are inside the \Game\Observer class, so you can now use $this
# Set the time and add a listener for post
$this->setTime();
# Since there is no indication of where some of these variables come from,
# this listen method will need attention...actually all the elements from the
# \Game and \Game\Observer need review, but they should be close enough to figure out
$this->listen($bank_verify,$pin);
?>
<form role="form" action="" method="post">
<?php
# $this->gameList()->getGames() should just return an array from your database
foreach($this->gameList()->getGames() as $row) {
$team_joined = $row['home_team'].' VS '.$row['away_team'];
$teams = $row['home_team'].'vs'.$row['away_team'];
?>
<h5><?php echo $team_joined; ?></h5>
<h5><span style="color:#f0ad4e;"><?php echo $row['match_day'].', '.$row['match_time'] ?></span></h5>
<input type="hidden" name="game[<?php echo $row['game_id'] ?>]" value="" />
<label><input type="radio" name="game[<?php echo $row['game_id'] ?>]" value="<?php echo $row['home_team']; ?>" />Home</label>
<label><input type="radio" name="game[<?php echo $row['game_id'] ?>]" value="draw" />Draw</label>
<label><input type="radio" name="game[<?php echo $row['game_id'] ?>]" value="<?php echo $row['away_team']; ?>" />Away</label>
<hr>
<?php
}
?>
<div class="form-group">
<input type="text" name="amount" class="form-control" placeholder="Enter your amount here" />
<input type="submit" name="submit" value="submit" class="btn btn-danger" style="margin-bottom: 10px;" />
</div>
</form>
When you process the post, you will retrieve data from the database based on the game id, so you should get all the variables you need except for ones that have no indication of origin in your script. Anyway, this is what I would do if I were you. One final note, I have not tested any of this, some of the methods are based off a framework I use, but I think it's a safer version of your script where sql injection is concerned, though you will have to research what some of this is doing...

Passing information using post method without session variables

I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>

$_POST within the class

I've got a class Posts which has public function displayPosts:
public function displayPosts($numberOf = 50){
$result = $this->mysqlResult($this->id);
$i = 1;
while ($post = mysql_fetch_object($result)) {
$added = new Time;
$elapsed = $added->displayElapsedSignificant($post->data);
echo "
<h1>$post->title</h1>
<i>$elapsed</i>
<p>$post->text</p>
<h3>...komentarze...</h3>";
$this->displayComments($post->id);
"<hr />";
if($i == $numberOf) break;
else $i++;
}
}
And the private function displayComments:
private function displayComments($id){
$postComments = new Comments;
switch($this->getElement($id, "comment_type")){
case 1:
if($_POST) {
echo addSecurity($_POST['comment']);
}
else {
echo '
Zostaw komentarz:
<form action="#" method="post">
<textarea id="comment"></textarea><br />
<input type="submit" value=" Dodaj komentarz " />
</form>
';
}
break;
case 2:
//kod dla fb
break;
case 3:
//kod dla obu
break;
default:
break;
}
}
My problem is that the form doesn't work: the $_POST is always empty. Any solution?
You need name attribute for form values to be send to server - like this:
<textarea id="comment" name="comment"></textarea>
$_POST is filled with name (not id) attributes as keys and values as values :)

PHP Math Pythagoras

Okay, I've coded this pythagoras-solver kind of thing, and I was wondering any ways I could improve it, or make it more efficient?
<?php
$sides = array('1' => 'Hypotenuse',
'2' => 'Adjacent',
'3' => 'Opposite');
function createSideDropdown($name) {
global $sides;
$option = "<select name='".$name."'>";
if(!empty($sides)) {
foreach($sides as $id => $sideDesc) {
$option .= "<option value='".$id."'>".$sideDesc."</option>";
}
} else {
die("Error fetching sides!");
}
$option .= "</select>";
echo $option;
}
try {
if(!empty($_POST['submit'])) {
if(empty($_POST['val1']) || empty($_POST['val2'])) {
throw new Exception("Please enter an integer in both boxes.");
}
if(!is_numeric($_POST['val1']) || !is_numeric($_POST['val2'])) {
throw new Exception("One of the numbers you entered is not a valid integer.");
}
$val1 = $_POST['val1'];
$val2 = $_POST['val2'];
$val1numtype = $_POST['val1type'];
$val2numtype = $_POST['val2type'];
$val1nametype = $sides[$val1numtype];
$val2nametype = $sides[$val2numtype];
if($val1numtype == $val2numtype) {
throw new Exception("The two sides of the triangle must be different");
}
if($val1nametype == "Hypotenuse" || $val2nametype == "hypotenuse") {
// work out a small side
$bignum = max($val1, $val2);
$smallnum = min($val1, $val2);
$sqTotal = ($bignum * $bignum) - ($smallnum * $smallnum);
$total = sqrt($sqTotal);
echo $bignum."² - ".$smallnum."² = ".$sqTotal."<br />
√".$sqTotal." = ".$total.$_POST['mes'];
} else {
// work out the hypotenuse
$sq1 = $val1 * $val1;
$sq2 = $val2 * $val2;
$sqTotal = $sq1 + $sq2;
$total = sqrt($sqTotal);
echo $val1."² + ".$val2."² = ".$sqTotal."<br />
√".$sqTotal." = ".$total.$_POST['mes'];
}
echo "<br /><br />"; // Seperate the working out from the input
}
} catch(Exception $e) {
echo $e->getMessage()."<br/><br/>";
}
?>
<form method='POST' action='index.php'>
Value 1: <input type='text' name='val1' />
<?php createSideDropdown("val1type"); ?>
<br /><br />
Value 2: <input type='text' name='val2' />
<?php createSideDropdown("val2type"); ?>
<br />
<select name="mes">
<option name="mm">mm</option>
<option name="cm">cm</option>
<option name="m">m</option>
<option name="cm">km</option>
</select>
<br />
<input type="submit" name="submit" />
</form>
?>
Well, one thing you can certainly do is:
HTML on its own and PHP on its own - separate that. And then, I would continue having a look at the rest.
Also, you could do your exceptions with JavaScript - I mean, use JavaScript to parse the text fields and write the errors with JavaScript. Rather than always submitting the form. - Still you should parse the fields in PHP as well.
Then, make a class out of it and make a proper documentation of it such as
/**
* This method does bla
* #param Int a
*/
Don't use globals - could be done with class attributes.

Categories