PHP: How to use switch statement to retrieve radio button values - php

I'm working on a homework assignment while learning PHP for the first time. Everything is working, except for my switch statement. My professor is asking-
"Modify index.php
Get the selected value from the "calculate" radio button you created
Add a switch statement to set values for:
only the average calculation if the user selected the "average" radio button
only the total calculation if the user selected the "total" radio button
both the average and total if the user selected the "both" button."
I'd like to provide my entire index.php file in case it's important to see everything-
<?php
//set default values to be used when page first loads
$scores = array();
$scores[0] = 70;
$scores[1] = 80;
$scores[2] = 90;
$scores_string = '';
$score_total = 0;
$score_average = 0;
$max_rolls = 0;
$average_rolls = 0;
$score_total_f = '';
$score_average_f = '';
//take action based on variable in POST array
$action = filter_input(INPUT_POST, 'action');
switch ($action) {
case 'process_scores':
$scores = $_POST['scores'];
// validate the scores
$is_valid = true;
for ($i = 0; $i < count($scores); $i++) {
if (empty($scores[$i]) || !is_numeric($scores[$i])) {
$scores_string = 'You must enter three valid numbers for scores.';
$is_valid = false;
break;
}
}
if (!$is_valid) {
break;
}
// process the scores
$score_total = 0;
foreach ($scores as $s) {
$scores_string .= $s . '|';
$score_total += $s;
}
$scores_string = substr($scores_string, 0, strlen($scores_string)-1);
// calculate the average
$score_average = $score_total / count($scores);
// format the total and average
$score_total_f = number_format($score_total, 2);
$score_average_f = number_format($score_average, 2);
$calculate = filter_input(INPUT_POST, 'calculate');
switch($calculate) {
case "average":
$message_average = $score_average_f;
break;
case "total":
$message_total = $score_total_f;
break;
case "both":
$message_average = $score_average_f;
$message_total = $score_total_f;
break;
default: die("Invalid type");
}
break;
case 'process_rolls':
$number_to_roll = filter_input(INPUT_POST, 'number_to_roll',
FILTER_VALIDATE_INT);
$total = 0;
$max_rolls = -INF;
for ($count = 0; $count < 10000; $count++) {
$rolls = 1;
while (mt_rand(1, 6) != $number_to_roll) {
$rolls++;
}
$total += $rolls;
$max_rolls = max($rolls, $max_rolls);
}
$average_rolls = $total / $count;
break;
}
include 'loop_tester.php';
?>
Also, here is part of the other file where I had to create radio buttons-
<h3>What do you want to do?</h3>
<input type="radio" name="calculate" value="average" checked> Average<br>
<input type="radio" name="calculate" value="total"> Total<br>
<input type="radio" name="calculate" value="both"> Both<br>
<label>Scores:</label>
<span><?php echo htmlspecialchars($scores_string); ?></span><br>
<label>Score Total:</label>
<span><?php echo $message_total; ?></span><br>
<label>Average Score:</label>
<span><?php echo $message_average; ?></span><br>
</form>
Thank you!
Again, everything is working fine when I test in XAMPP, just not the switch statement. I get no output of any kind.

EDIT: Disregard my original answer, I tested out your original syntax and it seems to work fine. Sorry, that was a mistake on my part, though I'd still say the new code is more elegant.
There seems to be an issue with a misplaced break; - Here is a full working code for to 'process_scores' case:
case 'process_scores':
$scores = $_POST['scores'];
// validate the scores
$is_valid = true;
for ($i = 0; $i < count($scores); $i++) {
if (empty($scores[$i]) || !is_numeric($scores[$i])) {
$scores_string = 'You must enter three valid numbers for scores.';
$is_valid = false;
break;
}
}
if (!$is_valid) {
break;
}
// process the scores
$score_total = 0;
foreach ($scores as $s) {
$scores_string .= $s . '|';
$score_total += $s;
}
$scores_string = substr($scores_string, 0, strlen($scores_string)-1);
// calculate the average
$score_average = $score_total / count($scores);
// format the total and average
$score_total_f = number_format($score_total, 2);
$score_average_f = number_format($score_average, 2);
$calculate = filter_input(INPUT_POST, 'calculate');
$score_average_f = number_format($score_average, 2);
$score_total_f = number_format($score_total, 2);
switch($calculate) {
case "average":
echo "Average: " . $score_average_f;
break;
case "total":
echo "Total: " . $score_total_f;
break;
case "both":
echo "Average: " . $score_average_f . "<br />";
echo "Total: " . $score_total_f;
break;
default: die("Invalid type");
}
break;
I'm not sure about other the other part of your code, but I tested this and got the intended results. If you still see nothing, check what's in your $_POST variables. Also as a general advice for debugging: in a situation like this, just go through your code and echo stuff out inside and outside of every loop or function you believe your code should reach, to see where it gets derailed. It may not sound too professional, but it sure gets the job done.

I'm doing the same exercise. You need to define your variables before all the code runs.
$scores_string = '';
$score_total = 0;
$score_average = 0;
$max_rolls = 0;
$average_rolls = 0;
$message_average = 0;
$message_total = 0;
After I defined variables, $message_average and $message_total, everything worked fine.

Related

For loop doesn't regen random string, stays the same

So I m trying to get a random string generator to work with a for loop. I have gotten it to loop the number of times it should but it refuses to generate a new string per loop. Can someone look at my code and show me where i went wrong? Also there is no way of using unqid so do not mention it please.
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$key = $_POST['keysd'];
if(isset($key) && is_string($key))
{
switch($key)
{
case "ksc";
$algor = "78.0000.".rnumstr(7);
break;
case "kpl";
$algor = "76.0000.".rnumstr(7);
break;
case "kfi";
$algor = "D01EB0A01472".rnumstr(1).strtoupper(ralphstr(3));
break;
}
$sum = $_POST['sum'];
$alg = $algor;
if(isset($sum))
{
for ($i = 0; $i < $sum; $i++)
{
echo $alg.'<br/>';
}
}
}
}
If you want to generate new $alg per loop's iteration, you must call your switch's code every iteration. Refactor your code:
function getRandomValue($key)
{
switch($key)
{
case "ksc":
return "78.0000.".rnumstr(7);
case "kpl":
return "76.0000.".rnumstr(7);
case "kfi":
return "D01EB0A01472".rnumstr(1).strtoupper(ralphstr(3));
}
}
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$key = $_POST['keysd'];
if(isset($key) && is_string($key))
{
$sum = $_POST['sum'];
if(isset($sum))
{
for ($i = 0; $i < $sum; $i++)
{
$alg = getRandomValue($key);
echo $alg.'<br/>';
}
}
}
}

PHP rand function giving empty values - still not working

I have this little tid-bit of my code, which is eventually sent to a MySQL database. The rest of the code is sound, but this code likes to give me empty data some of the time. Is there any way to prevent this from happening?
Edit: Here's the whole chunk
//random Species
$sp_one = mt_rand(1,10);
$one_species = "Water Leaper";
//random Genetics
if($one_species == "Water Leaper")
{
$one_gene = mt_rand(1,5);
if($one_gene < 3)
{
$one_genetics = "1";
}
else if($one_gene < 5)
{
$one_genetics = "2";
}
else
{
$one_genetics = "3";
}
}
//random Gender
$one_sex_num = mt_rand(1,2);
if($one_sex_num == 1)
{
$one_gender = "Female";
}
if($one_sex_num == 2)
{
$one_gender = "Male";
}
//Entering it
$sql="INSERT INTO creatures (species, sex, location, genetics)
VALUES('{$one_species}','{$one_gender}', 's1','{$one_genetics}')";
mysqli_query($con,$sql);
First, your if clauses seem a bit redundant. More concise code:
if ($one_gene <3) { $one_genetics = "1"; }
elseif ($one_gene <5) { $one_genetics = "2"; }
else { $one_genetics = "3"; }
This should always return a value - if everything else fails, "3".
Maybe better even:
$one_genetics = ($one_gene + 1) / 2; // integer division
I don't know what you are doing exacly but maby you can take a look at this:
<?php
$animals = array();
$animals[] = array('dog', 78, array('Komondor','Old English Sheepdog'));
$animals[] = array('Drosophila', 8, array('Vestigal','Ebony'));
$number_animals = count($animals) - 1;
$list_size = 30;
for($q = 1; $q <= $list_size; $q++){
$rand = rand(0, $number_animals);
$animal = $animals[$rand];
$number_species = count($animal[2]) - 1;
$rand = rand(0, $number_species);
$randsex = rand(0, 1);
$species = $animal[2][$rand];
$sex = ($randsex ? 'male' : 'female');
$genes = $animal[1];
echo "$q: $species - $sex - $genes <br>";
}
?>
See a live demo at: here
It pics random animals with specs if you want you can modify to your own wishes.

How can I "limit" the page numbers of a forum/blog in PHP

I'm trying to fix something with which I'm not familiar with and don't know how to proceed. The forum on which I'm working is suppose to show under "TOP 50" only the most commented topics (2 pages by 25 topics) but it shows all topics (by 25) without any limitation of the pages. I need only the first 2 pages - but don't know how to get rid of the others?
I'm even not sure that the below code is the responsible one but please have a look and give me a hint if you see any solution.
This is the code:
{
public function __construct()
{
parent::__construct();
}
public function get_forum()
{
if ($_GET['l'] && ($_GET['l'] == 'leng' || $_GET['l'] == 'lrus' || $_GET['l'] == 'lde' || $_GET['l'] == 'ltr'))
$l = substr($_GET['l'], 1);
else
$l = 'eng';
(isset($_GET['num'])) ? $page = intval($_GET['num']) : $page = 1;
$id_user = intval($_SESSION['user_id']);
$lang = language::getLang();
if ($_GET['el']) {
switch ($_GET['el']) {
case 'categories':
return $this->getCategories($l);
break;
case 'top':
$top_lang = $_GET['ln'];
$c = $this->db->selectAssoc($this->db->Select('*', 'forum_categories ,forum_thems', "`forum_categories`.`lang` = '" . $l
. "' AND `forum_thems`.`id_categories` = `forum_categories`.`id`"));
$total_pages = count($c) / 25;
$p = "<div class=\"pageCounter_box\">Pages:";
if (empty($_GET['p'])) {
$_GET['p'] = 1;
}
for($i=1; $i<$total_pages+1; $i++){
if ($i == $_GET['p']) {
$class = 'class="active_page"';
}
$p .= "<a href=\"$top_lang/smoke/{$_GET['l']}/top?p=$i\" $class>$i</a>";
}
$p .= "</div>";
return $this->getTop($l) . $p;
break;
I think you could do a check in there of If ($total_pages > 2) { $total_pages = 2};
$c = $this->db->selectAssoc(
$this->db->Select('*', 'forum_categories ,forum_thems', "`forum_categories`.
`lang` = '" . $l. "' AND `forum_thems`.
`id_categories` = `forum_categories`.`id`"));
$total_pages = count($c) / 25;
if ($total_pages >2) { //limit to two pages
$total_pages = 2;
}
$p = "<div class=\"pageCounter_box\">Pages:";
if (empty($_GET['p'])) {
$_GET['p'] = 1;
}
"thanks a lot - great help! Do you further see why both pages might show active (page counter shows both active) when showing page 1? Page 2 is fine, there only Page 2 shows active..."
The $class variable is staying set, you need to have an else that sets the class to an empty string
for($i=1; $i<$total_pages+1; $i++){
if ($i == $_GET['p']) {
$class = 'class="active_page"';
} else {
$class = '';
}
$p .= "<a href=\"$top_lang/smoke/{$_GET['l']}/top?p=$i\" $class>$i</a>";
}

PHP - reordering using loop

I have three variables:
$title_order = 1;
$image_order = 2;
$content_order = 3;
and user can rearrange/reorder above variable, Like:
$title_order = 2;
$image_order = 1;
$content_order = 3;
Now, as per this variable I want to reorder below HTML
<h1><?php title() ?></h1>
<figure><?php thumbnail() ?></figure>
<details><?php thumbnail() ?></details>
how to show this as per variable number, like:
<figure><?php thumbnail() ?></figure> // show image 1st if $image_orer = 1;
<h1><?php title() ?></h1> // show h1 in 2nd if $title_order = 2;
<details><?php thumbnail() ?></details> // show h1 3rd if $content_order = 3;
please note user can set variable to anything between 1,2 and 3.
so please tell me how do i achieve this.
$result = '';
for ($i = 1; $i <= 3; ++$i) {
switch ($i) {
case $title_order:
$result .= '<h1>' . title() . '</h1>';
break;
case $image_order:
$result .= '<figure>' . thumbnail() . '</figure>';
break;
case $content_order:
$result .= '<details>' . thumbnail() . '</details>';
break;
}
}
echo $result;

MySQL Select Not Returning resource

I am having a small problem with my PHP MySQL Select. The function is inside of a PHP class. Here is the error I get:
Warning: mysql_fetch_array() expects parameter 1 to be resource,
integer given in C:\xampp\htdocs\include\database.php on line 59
Warning: extract() expects parameter 1 to be array, null given in
C:\xampp\htdocs\include\database.php on line 59
The function just simply updates the database to show what browser and OS they visited the site with. The function is called from another file that is called by an AJAX call that uses POST to send the data about the OS and browser that was gathered from a Javascript file. It only fails if there is an entry of the IP address already in the database. If there is no IP Address entry in the database it succeeds in creating one.
Here is my code:
function addStat($browser, $os){
$IE = 0; $Firefox = 0; $Safari = 0; $Opera = 0; $Chrome = 0; $otherb = 0;
$Windows = 0; $Linux = 0; $Mac = 0; $Android = 0; $iOS = 0; $otheros = 0;
$ql = 0; $totalVisits = 0;
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$q1 = mysql_query("SELECT * FROM " . DB_STATS . " WHERE ip='$ip'", $this->connection);
if (mysql_num_rows($q1)==0){
$browser = mysql_real_escape_string($browser);
$os = mysql_real_escape_string($os);
switch($browser){
case "Internet Explorer":
$IE += 1;
break;
case "Firefox":
$Firefox += 1;
break;
case "Safari":
$Safari += 1;
break;
case "Opera":
$Opera += 1;
break;
case "Chrome":
$Chrome += 1;
break;
default:
$otherb += 1;
break;
}
switch($os){
case "Windows":
$Windows += 1;
break;
case "Mac OS X":
$Mac += 1;
break;
case "Linux":
$Linux += 1;
break;
case "Android":
$Android += 1;
break;
case "iOS":
$iOS += 1;
break;
default:
$otheros += 1;
break;
}
$q = $this->query("INSERT INTO " . DB_STATS . " VALUES (null, '$ip', '$Chrome', '$IE', '$Firefox', '$Opera', '$Safari', '$otherb', '$Windows', '$Mac', '$Linux', '$Android' , '$iOS' , '$otheros', 1)");
if ($q == true){
return(1);
}
else{
return(0);
}
}
else if (mysql_num_rows($q1)==1){
extract(mysql_fetch_array($ql));
switch($browser){
case "Internet Explorer":
$IE += 1;
break;
case "Firefox":
$Firefox += 1;
break;
case "Safari":
$Safari += 1;
break;
case "Opera":
$Opera += 1;
break;
case "Chrome":
$Chrome += 1;
break;
default:
$otherb += 1;
break;
}
switch($os){
case "Windows":
$Windows += 1;
break;
case "Mac OS X":
$Mac += 1;
break;
case "Linux":
$Linux += 1;
break;
case "Android":
$Android += 1;
break;
case "iOS":
$iOS += 1;
break;
default:
$otheros += 1;
break;
}
$totalVisits += 1;
$q = $this->query("UPDATE " . DB_STATS . " set Chrome='$Chrome', IE='$IE', Firefox='$Firefox', Opera='$Opera', Safari='$Safari', otherb='$otherb', Windows='$Windows', Mac='$Mac', Linux='$Linux', Android='$Android' , iOS='$iOS' , otheros='$otheros', totalVisits='$totalVisits'");
if ($q == true){
return(1);
}
else{
return(0);
}
}
else{
return(-1);
}
}
I hope everything made sense and that someone will help.
I see it now -- you used $ql (lower case L) when you intend to use $q1. Let this be a lesson against using very short variable names or very similar names.
// $ql was initialized to 0
$ql = 0; $totalVisits = 0;
// $q1 holds the result resource
extract(mysql_fetch_array($q1));
It is not advisable to call extract() on the output of mysql_fetch_array() unless you also specify the second parameter MYSQL_ASSOC as the fetch type. By default it returns both numeric and associative indices for each column.
extract(mysql_fetch_array($q1, MYSQL_ASSOC));
// Or better
extract(mysql_fetch_assoc($q1));
In general, I would probably advise against using extract() in most any situation, since it results in numerous variables dumped into the global namespace, in particular when you have done SELECT * without being specific about which columns are selected. Better to access them via their array:
$row = mysql_fetch_assoc($q1);
echo $row['browser'];

Categories