$_POST within the class - php

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 :)

Related

php: how to change array value (text)

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!

Switch Statements not working

I'm trying to use the switch statements but it's not working. My problem is for example i input LazyBoy in the textbox, that should echo LazyBoy else echo another string.
<?php
$classmap = $_POST['classmap'];
switch ($classmap) {
case "LazyBoy":
echo "You're Lazy!";
break;
case "GrayHounds":
echo "You're Gray!";
break;
}
?>
Here is the form -
<form action="checkout.php" method="post" >
<input type="hidden" name ="classmap" value="<?php include('db.php');
$origin = $_POST['origin'];
$class = $_POST['class'];
$daten = $_POST['daten'];
$result = mysql_query("SELECT * FROM route WHERE route LIKE '%$origin%' AND type LIKE '%$class%' AND date LIKE '%$daten%' ");
while($row = mysql_fetch_array($result))
{
echo $row['type'];
} ?>">
</form>
You just need to check if the post variable is set and/or add a default case :
if(isset($_POST['classmap'])) {
$classmap = $_POST['classmap'];
switch ($classmap) {
case "LazyBoy":
echo "Your Lazy!";
break;
case "GrayHounds":
echo "Your Gray!";
break;
default:
echo "Something";
break;
}
}
else {
echo "Something";
}
Make sure you post to the right script.
Try to put default statement to debug.
$classmap = $_POST['classmap'];
switch ($classmap) {
case "LazyBoy":
echo "You're Lazy!";
break;
case "GrayHounds":
echo "You're Gray!";
break;
default:
echo "does not match with previous cases";
}
First you have to post values to define the classmap index.
<form method="post">
<input type="text" name="classmap" value="LazyBoy"/>
<input type="submit" value="submit"/>
</form>
<?php
$classmap = (isset($_POST['classmap']) ? $_POST['classmap'] : null);
switch ($classmap) {
case "LazyBoy":
echo "You're Lazy!";
break;
case "GrayHounds":
echo "You're Gray!";
break;
}
?>
Your Code is correct.
I guess there is a Problem with the $_POST.
Try to verify it.
$classmap = "LazyBoy";

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>

How to iterate through an array then replace data of a matching id

Okay so what i am trying to do is Iterate through Json decoded array then search for an ID(key) then post that data into a form for editing then encode it then save it it seems like such an easy task however i am not using a data base or java or java script i have to do this using only Json, PHP and HTML my main code(Controller) file is as follows
<?php
$file_name = 'engagements.json'; // Serialized speaking engagments
/**
* Controller for Speaking Engagements
*/
if (!isset($_REQUEST['act']) || !$action = $_REQUEST['act']){
$action = 'list';
} //End If
switch ($action) {
case 'list': // List
$json_data = file_get_contents($file_name);
if (!$engagements = json_decode($json_data, true)) { // Convert serialized data to array
$engagements = array();
} //End If
include 'engagements_list.phtml';
break;
case 'view': // View
$json_data = file_get_contents($file_name);
$temp_array = json_decode($json_data);
foreach($temp_array as $key=>$id){
if($id->ID == 2){
echo "got it \n";
echo "ID: $id->ID \n";
echo "Title: $id->Title \n";
echo "Description: $id->Description \n";
}// End If
}
break;
case 'add': // Add
$temp_array = array();
$file = file_get_contents($file_name);
$json_data = json_decode($file);
$high_value = count($json_data);
$high_value++;
$temp_array['ID'] = $high_value;
$temp_array['Title'] = $_POST['Title'];
$temp_array['Description'] = $_POST['Description'];
$json_data[] = $temp_array;
file_put_contents($file_name, json_encode($json_data));
include 'engagements_add.phtml';
break;
case 'edit': // Edit
$file = file_get_contents($file_name);
$json_data = json_decode($file, true);
// what comes next here
include 'engagements_edit.phtml';
break;
case 'delete': // Delete
break;
default:
throw(new Exception('Invalid action given'));
break;
}//End Switch
exit;
<!-- Edit View -->
<form action="engagements.php?act=edit?ID=<?php $_GET['ID']?>" method="get">
<table>
<tr><td><input type="hidden" name="ID"></td></tr>
<tr><td><input type="text" style="width:500px;" name="Title"></td></tr>
<tr><td><textarea cols="40" rows="2" style="width: 500px; height:250px;" name="Description"></textarea></td></tr>
<tr><td><input type="submit" name="Submit" value="Submit"/></td></tr>
</table>
</form>
please help me i have searched everywhere for an answer but can find any resources that explain how to do this properly
Tiny one point.
<form action="engagements.php?act=edit?ID=<?php $_GET['ID']?>" method="get">
I'm assuming you meant to type like this:
<form action="engagements.php?act=edit&ID=<?php echo $_GET['ID']?>" method="get">
The $_GET statement was missing an echo, too.
UPDATE:
I notice php close tag ?> missing until EDIT VIEW. And 'view' part in switch, why you echo ID property? It might be following:
echo "ID: $id['ID'] \n";

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