PHP echo doesn't show up in webpage - php

So im fairly new in coding HTML CSS and PHP and now im focusing PHP.
Our professor asked us to incorporate PHP codes in our website (no database) and im trying to print a an array using a for loop and echo.
the problem is that the echo doesn't show in the webpage and I am now lost
below is my codes:
<html>
<head>
<title>PHP Loops and Sorts</title>
<body>
<h1>PHP Loops and Sorts</h1>
<div class="container">
<?php
$dogs=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$cats=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$birds=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$fishes=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($array,$size){
$size = count($array);
return $size;
}
if(isset($_POST['btnShow']) )
{
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick,$size);
for(&x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
}
?>
Breeds of different kinds of animals. Select what animal's breed to be shown:<br>
<select name="formAnimal">
<option value="">Choose animal</option>
<option value="dogs">Dog</option>
<option value="cats">Cat</option>
<option value="birds">Bird</option>
<option value="fishes">Fish</option>
</select><br><br>
<div style="margin:auto,text-align:center;text-align:center">
<INPUT TYPE = "Submit" Name = "btnShow" VALUE = "Show List"> 
<INPUT TYPE = "Submit" Name = "btnAsc" VALUE = "Show Ascending"> 
<INPUT TYPE = "Submit" Name = "btnDes" VALUE = "Show Descending">
</div>
<?php
echo $size
?>
</div>
</body>
</html>

You need to close your head tag before your body tag.
You also don't need to pass in size to your method count size.
function countsize (&array) {
return count(&array);
}

if(isset($_POST['btnShow']) ) are you sure it is set ?
From what we have in your code you can't even POST, you are missing your form tags
Try wrapping your inputs with :
<form method="POST">
<!--inputs-->
</form>

Your syntax for the for loop is incorrect. Check out the php documentation
Also the $size variable is never declared in the scope you are using it.

Didn't get how you're using $arrsize but you used &x instead of $x while initializing loop.
for($x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}

change this lines of code:
$dogs=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$cats=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$birds=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$fishes=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($array,$size){
$size = count($array);
return $size;
}
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick,$size);
for(&x = 0,$x<$arrsize,$x++){
echo $arraypick[$x] . "<br>";
}
To :
$animalArray['dogs']=Array("Labrador Retriever","German Shepherd","Bulldog","Golden Retriever","Poodle","Beagle","Rottweiler","Yorkshire Terrier","Siberian Husky","Dachshund","Chihuahua","Pug","Great Dane","Dobermann","Shih Tzu");
$animalArray['cats']=Array("Persian","Siamese","Maine Coon","Ragdoll","Sphynx","British Shorthair","Abyssinian","Bengal","Scottish Fold","Himalayan","Russian Blue","Siberian","Munchkin");
$animalArray['birds']=Array("Canaries","Budgies","Finches","Cockatiels","Quaker Parakeets","Pionus Parrots","Poicephalus Parrots","Amazon Parrots","Pyrrhura Conures","Peach-Faced Lovebirds");
$animalArray['fishes']=Array("Koi","Fantail","Oranda","Comet","Black Telescope","Butterfly Tail","Ryukin","Goldfish","Lionhead","Mirror Carp");
function countsize($index){
return count($animalArray[$index]);
}
$arraypick=$_POST['formAnimal'];
$arrsize = countsize($arraypick);
for($x = 0;$x<$arrsize;$x++){
echo $animalArray[$arraypick][$x] . "<br>";
}

Related

What's wrong with this calculation?

Consider this markup:
<?php
$drill = 0;
$result = '';
$dynamicD = rand(5,15);
$num01 = $dynamicD-4;
$placeholder = $num01.'+4';
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["drill"])){
$humanErr = "Empty";
}
else {
$drill = $_POST["drill"];
if($drill !== $dynamicD) {
$result = "No";
}
else {
$result = "Yes";
}
};
};
?>
<!doctype html>
<html>
<body>
<p>Correct Answer: <?php echo $dynamicD ?></p>
<p>Does this work? <?php echo "$result";?></p>
<form method="post">
<fieldset>
<label for="drill">Can you solve it?</label>
<input type="text" name="drill" id="drill" maxlengh="2" placeholder="<?php echo $placeholder ?>" required="true" />
</fieldset>
<button type="submit" name="check">Check</button>
</form>
</body>
</html>
Basically it generates "random" number, insert it as a drill, and then let the user submit his answer. The problem is that the answer is always "NO"*.
I tried to separate the condition to this:
if($drill > $dynamicD) { $result = "bigger" }
elseif ($drill < $dynamicD) { $result = "smaller" }
and so on - but can't understand the logic of the $result (sometime bigger, sometime smaller, but i ALWAYS enter $dynamicD...).
What am i doing wrong here???
EDIT:
As the comments points, every time the page submit it generates new numbers. The first time the code execute is the only time that correct answer would be equal to the numbers that display. After the first submit there is a gap.
Note for future readers: The above code extracted and simplified from bigger and much complex system. Not something that anyone would want to just copy-paste.
The solution i choose was to store the dynamically created vars on a session and re-declare if the answer is correct.
Would love to hear about other ways (not client side).

PHP code for calculator. validated but not working

So I have a calculator coded in PHP and I have validated it but there is a problem with this, its not working. I have used server side validation. Validation works well. But it doesn't do any work,for example, when I give an input like 2+8, it gives an output of 8888. This is very confusing. Please help me out with this. Thanks.
HTML page is here:
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form method = "post" action = "calc.php">
<input type = "text" name = "val_1"/>
<select name="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type = "text" name = "val_2"/>
<input type = "submit" value = "calculate" name = "checker"/>
</form>
</body>
</html>
And here is the PHP code.
<?php
if(isset($_POST['checker'])) {
#Clean all values
function cleanStr($str){
$str = trim($str);
$str = addslashes($str);
$str = htmlspecialchars($str);
return $str;
}
$val_1=cleanStr($_POST['val_1']);
$val_2=cleanStr($_POST['val_2']);
$operator=$_POST['operator'];
function emptyFileds($ar){
if(!is_array($ar)){
echo "It must be an array";
return false;
}
#loop through each field to check for empty values
foreach($ar as $key => $value){
$value = CleanStr($value);
if(empty($value)){
echo $key . " must not be empty";
return false;
}
}
return true;
}
if(!emptyFileds($_POST)){
exit();
}
if($operator==="+"){
echo "Sum is " . $val_1+$val_2;
}
}
?>
Please change the original line
echo "Sum is " . $val_1+$val_2;
to
echo "Sum is " . ($val_1+$val_2);
It's a operator precedence issue as . is executed first. Therefore you append 2 to "Sum is " and then increment the string by 8 which results in this odd behavior.
Also, some nitpicking on your code, I will just name 3 issues:
requesting a parameter with cleanStr() is not a good idea, it's better to use
$val_1 = (int)trim($_POST['val_1']);
as $val_1 will be an integer after that line. This might be important for later development e.g. to compare numbers.
indent correctly, reading your code is hurting my eyes
the whole emptyFileds()thing is unnecessary, simply check whether the 3 parameters are filled or not, it's simple and it's readable.

PHP - Having a placeholder 'echo' so to speak

<?
//LUHN ALGORITHM PHP CONVERSION
// CREDIT CARD NUMBER CHECKER BY JACK BELLAMY - JACKBELLAMY.CO.UK
//----------- RETREIVE THE STRING FROM THE FORM POST -------------//
$var = $_POST['cardnumber'];
//----------- SPLIT THE 16 CHARACTOR STRING INTO INDIVIDUAL CHARACTERS AND ASSIGN TO INDIVIDUAL VARIABLES ---------------//
$n0 = $var[0];
$n1 = $var[1];
$n2 = $var[2];
$n3 = $var[3];
$n4 = $var[4];
$n5 = $var[5];
$n6 = $var[6];
$n7 = $var[7];
$n8 = $var[8];
$n9 = $var[9];
$n10 = $var[10];
$n11 = $var[11];
$n12 = $var[12];
$n13 = $var[13];
$n14 = $var[14];
$n15 = $var[15];
// ---------------------CHECKING THE CARDNUMBER FORM POST SUBMITS ALL VALUES PROPERLY
/*
echo $n0;
echo $n1;
echo $n2;
echo $n3;
echo $n4;
echo $n5;
echo $n6;
echo $n7;
echo $n8;
echo $n9;
echo $n10;
echo $n11;
echo $n12;
echo $n13;
echo $n14;
echo $n15;
*/
//-------ASSIGNING THE NEW VARIABLE VALUES ------------//
$n14_new = ($n14*2);
$n12_new = ($n12*2);
$n10_new = ($n10*2);
$n8_new = ($n8*2);
$n6_new = ($n6*2);
$n4_new = ($n4*2);
$n2_new = ($n2*2);
$n0_new = ($n0*2);
//!-----!------!//
//------------------------TESTING WITH THE NEW VARAIBLE *2
/*
echo $n0_new;
echo $n1;
echo $n2_new;
echo $n3;
echo $n4_new;
echo $n5;
echo $n6_new;
echo $n7;
echo $n8_new;
echo $n9;
echo $n10_new;
echo $n11;
echo $n12_new;
echo $n13;
echo $n14_new;
echo $n15;
*/
//--------- THE MATHS FOR THE COMPLETE SUM ------------ //
$isitlegit = ($n0_new+$n1+$n2_new+$n3+$n4_new+$n5+$n6_new+$n7+$n8_new+$n9+$n10_new+$n11+$n12_new+$n13+$n14_new+$n15);
//!----MATHS-----!//
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="veri-styles.css"
</head>
<body>
<div class="container">
<div class="main-wrapper">
<div id ="verification-wrapper">
<form action="" method="post" enctype="application/x-www-form-urlencoded">
<div id="input-holder">
<input name="cardnumber" type="text" class="input-style" placeholder=""> </input>
<button class="button-style">Verify my card</button>
</div>
</form>
<div class="result-class">
<?php
if(isset($isitlegit) && ($isitlegit % 5 == 0)) { // it's good
$new = "<img src='correct.jpg' />";
} elseif(isset($isitlegit) && ($isitlegit % 5 != 0)) { // it's bad
$new = "<img src='incorrect.jpg' />";
} elseif(!isset($isitlegit)) { // make sure this is not set
$new = "<img src='card-number-required.jpg' />";
}
echo $new;
?>
</div>
</div>
</div>
</body>
</html>
You have three states you need to account for, 'open', 'correct', and 'incorrect' To do that you start with an 'open' state.
$new = "<img src='please_enter your card number.jpg' />";
echo $new;
You would use that in the first condition of your test -
if(isset($var) && ($isitlegit % 5 == 0)) { // it's good
$new = "<img src='correct.jpg' />";
} elseif(isset($var) && ($isitlegit % 5 != 0)) { // it's bad
$new = "<img src='incorrect.jpg' />";
} else { // the default view
$new = "<img src='please_enter your card number.jpg' />";
}
echo $new;
Once submitted you can only have one of two states, never to return to the default.
In addition you have left your stylesheet declaration un-closed. Please change it to this -
<link rel="stylesheet" type="text/css" href="veri-styles.css" />
if(false===$submitted){
echo "Please type your card details here";
} else {
if($isitlegit % 5 == 0) {
$new = "<img src='correct.jpg' />";
echo $new;
}
else {
$new = "<img src='incorrect.jpg' />";
echo $new;
}
}
The best way I can think of to achieve this is with AJAX. Create a div on your page where your initial message is displayed, and then use an AJAX call to submit the form data to a script you'll use to validate it, and within that script, echo either a "Success! Your card has been verified" or a "Unable to validate your card" message. Then have your AJAX function change the .innerHTML of the div to the responseText element. You can see this answer for a good starting point, as well as a note about using the jQuery library to simplify your AJAX implementation.
Edit: In response to another user's downvote, here's some code.
First, let's give your HTML form a call to an AJAX object we'll create. So change your HTML form code to this:
<form onSubmit="return process()">
process() is a javaScript function we're going to set up later with the AJAX call. You already have a div established where you want this data to appear, but we need to give it an id, so change:
<div class="result-class">
please enter your card number<img src='correct.jpg' />
</div>
to this:
<div class="result-class" id="result">
Please enter your card number.
</div>
And also assign an id to your text input:
<input name="cardnumber" type="text" class="input-style" placeholder="" id="cardnumber"> </input>
Now we'll create the javaScript function. (This is easier with jQuery, but I wrote it in plain javaScript so you won't need the dependancy if you're not familiar with how to use jQuery.
function process(){
var xmlhttp = new XMLHttpRequest();
var cardnumber = document.getElementById("cardnumber").value;
var result = document.getElementById("result");
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
result.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","validate.php?cardnumber=" + cardnumber,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
return false;
}
Now, use whatever php script you were going to use to validate the cc# and save it as a separate script called validate.php Use $_GET['cardnumber'] variable to fetch the cardnumber data sent from the form, run it through whatever validation process you are using. Use an if statement to create the responseText element for our AJAX function. You might have your script set some variable to boolean true or false to check this. I'll use $validated here.
if($validated){
echo 'Your card has been verified!';
} else {
echo 'Unable to validate your card.';
}
The AJAX function will change the text inside the "result" div to whatever text is echoed by your validate.php script.
This should get you on the right track, barring any syntax errors, I just wrote this all off the cuff.

PHP array sort / select option form

I have a form in PHP. It is unsorted. I would like to sort it. How would I go by it. This is the following PHP code I have. Thanks for help in advance.
<select id="school_name" name="school_name">
<option value="">Select School</option>
<?php for($c=0; $c<sizeof($school_details); $c++){?>
<option value="<?php echo stripslashes($school_details[$c]["title"]); ?>"
<?php if($school_details[$c]["title"]==$appInfo["school_name"]){?> selected="selected" <?php } ?> ><?php echo stripslashes($school_details[$c]["title"]); ?>
</option>
<?php } ?>
</select>
try somthing like this:
$str = "<select id='school_name' name='school_name'>";
$options = "";
for($i = 0; $i<10;$i++)
{
$RandomNum = rand(0, 100);
$options = "" . $options . ("<option value='$RandomNum'>&nbsp" . $RandomNum . "&nbsp </option>\n");
}
$optionsArray = explode("\n", $options);
natsort($optionsArray);
$sorted_option = implode("|",$optionsArray);
$select = $str.$sorted_option."</select>";
echo $select;
PHP provides a number of methods for sorting: http://www.php.net/manual/en/array.sorting.php
You could implement a user defined sort to achieve this. Assuming you want to sort by the value of the 'title' element you would simply add this before your opening select tag:
<?php
uasort($school_details,'cmp');
function cmp($a,$b){
if($a['title'] == $b['title']){return 0;}
return ($a['title'] < $b['title']) ? -1 : 1;
}
?>

Session Variables are Null

I've searched and tried over a dozen suggestions from similar issues on this site, but only a little closer to resoluton.
I am starting out with HTML & PHP so this is a very simplistic couple of scripts.
I am setting up an array with math questions (to test my 9 year old son).
The first script "mathtest.php" sets up the array and sets a couple of variables in the $_session global variable and then a form submits an answer to the question to "mathtest1.php".
My $_session variables are lost when I get to "mathtest1.php".
Please help. I know I can do something with cookies, but I really want to advance in my understanding of sessions.
Here's the 2 scripts:
"mathtest.php":
<?php
session_start();
?>
<html>
<title>Math Test</title>
<head>Math Test</head>
<body>
<?php
$arrayindex = 0;
for ($L = 1; $L <= 12; $L++) {
for ($R = 12; $R >= 1; $R--) {
$setupquestions[$arrayindex] = $L.'*'.$R;
$arrayindex++;
}
}
$_session["questions"] = $setupquestions;
$_session["randomkey"] = array_rand($_session["questions"],1);
?>
<form action="mathtest1.php" method="post">
What is <?php echo $_session["questions"][$_session["randomkey"]]." ?" ?>
<input type="text" name="answer">
<input type="submit" name = "submit">
</form>
</body>
</html>
The script above works as expected, but the script below has null values for the session variables I"m trying to access and use.
"mathtest1.php":
<?php
session_start();
?>
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$answer = $_POST['answer'];
$result = eval("return $_session[questions]$_session[randomkey];");
echo "result = ".$result."<br />";
if ($answer == $result) {
echo "Correct!!";
}
else {
echo "WRONG!!";
}
}
$_session["randomkey"] = array_rand($_session["questions"],1);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is <?php echo $_session["questions"][$_session["randomkey"]]." ?" ?>
<input type="text" name="answer">
<input type="submit" name = "submit">
</form>
</body>
</html>
Other details:
OS X, Chrome Browser, latest version of PHP
XAMPP installation & scripts are on the same laptop as XAMPP, not on an external server.
session cookies are ON
...Trans_ID is ON
I have read & write access to the session save path.
$_SESSION should be in uppercase.
try uppercase!
http://php.net/manual/en/reserved.variables.session.php
$_SESSION
Unlike function names...
function bar(){
}
function Bar(){
}
...
Fatal error: Cannot redeclare Bar() (previously declared in C:\tmp\test.php:3) in C:\tmp\test.php on line 7
... variable names are case-sensitive in PHP:
$foo = 1;
$Foo = 2;
$FOO = 3;
var_dump($foo, $Foo, $FOO);
...
int(1)
int(2)
int(3)
This applies to predefined variables as well, including $_SESSION.

Categories