2 checkboxes for ball's area and circumference - php

I have an html file with form with 2 checboxes in it, and I wanted to calculate the area and circumference of ball, but the form doesn't return any value...
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Ball</title>
<meta charset="UTF-8">
</head>
<body>
<form action="test.php" method="post">
Enter radius: <br><br>
<input type="text" name="radius"> <br><br>
Area:
<input type="checkbox" name="check_list[]" value="value 1"><br>
Circumference:
<input type="checkbox" name="check_list[]" value="value 2"><br>
<button type="submit">Calculate</button>
</form>
</body>
</html>
And the PHP file (I used foreach loop):
<?php
$radius = $_POST['radius'];
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
if ($check == "0")
{
$result1 = 4*3.14*($radius*$radius);
echo "Area: " . $result1."<br>";
}
if ($check == "1")
{
$result2 = 4/3*3.14*($radius*$radius*$radius);
echo "Circumference: " . $result2 . "<br>";
}
}
?>
Why it doesn't work? What am I doing wrong?

Your current values of area and circumference check boxes are "value 1" and "value 2". Those are the values you get in the php code.
So in the if condition check for those values. i.e if($check=="value 1") or if($check ==" value 2").
But a better practice is to change the value check boxes to just "0" and "1".
It will be more easier.

Change the values of the checkbox items to value="0" for the area and value="1" for the Circumference
Then change the condition on your loop:
foreach($_POST['check_list'] as $option => $check)

Related

PHP if/else statement acting weird

I'm relativity new to php and just testing out some code. The odd thing is that the code both does/doesn't work. The code should check a MySQLi database to determine the state of the check box and then apply that state to the checkbox. What the code currently does is designate the checkbox state based solely off the value of the if condition, regardless of the MySQLi database values.
Here is the code for the html page, it's the if statement near the bottom that's causing issues;
<?php
include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$sql_1 = "SELECT * FROM test2;";
$results = mysqli_query($conn, $sql_1) or die('Error getting data.');
echo(string) "<table>";
echo "<tr><th>state</th><th>id</th></tr>";
while($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['state'];
echo "</td><td>";
echo $row['id'];
echo "</td></tr>";
}
echo "</table>";
?>
<form action="includes/checkbox.inc.php" method="post">
<input type="hidden" name="checkbox1" value="0">
<input type="checkbox" name="checkbox1" value="1"
<?php
$sql_2 = mysqli_query($conn, "SELECT state FROM test2 WHERE id = '0'") or die('Error getting data.');
if ($sql_2 == "0") {
echo "checked";
} else {
echo " ";
}
mysqli_close($conn);
?>
> Item 1<br>
<input type="hidden" name="checkbox2" value="0">
<input type="checkbox" name="checkbox2" value="1" checked> Item 2<br>
<input type="submit" name="Submit" value="Submit">
</form>
<br>
Reset<br>
</body>
</html>
The odd thing about this code is that the if ($sql_2 == "0") results in the checkbox remaining unchecked, but changing the 0 to a 1, if ($sql_2 == "1") results in the checkbox remaining checked. Both results are regardless of what the database shows.
I know all the other bits of code work, because when I check the checkbox and submit, it updates the database and displays it correctly (the reverse is also true).
If anyone knows why if ($sql_2 == "0") is not working, please let me know. I've even checked other stack overflow postings, and as far as I can tell, everything should be coded properly.
Edit:
I should have stated that in the above question, changing the = to == or reversing the order doesn't fix the problem. The if statement still only returns the else statement.
I've done additional research and think that the issue is related to the use of mysqli_query to retrieve the data, as it should likely be mysqli_fetch_row.
if ($sql_2 = "0") will make the value of $sql2 to '0' and this condition will be always true
change it to
if ($sql_2 == "0")
to prevent the accidental assignment you can do like below
if ("0"==$sql_2)
ISSUE FIXED
The solution was to add a mysqli_data_seek() to the php, below is the working code.
<?php
include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$sql_1 = "SELECT * FROM test2;";
$result_1 = mysqli_query($conn, $sql_1) or die('Error getting data.');
echo(string) "<table>";
echo "<tr><th>state</th><th>id</th></tr>";
while($row = mysqli_fetch_array($result_1, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['state'];
echo "</td><td>";
echo $row['id'];
echo "</td></tr>";
}
echo "</table>";
$query_1 = "SELECT state, id FROM test2 ORDER BY id";
$sql_3 = mysqli_query($conn, $query_1) or die('Error getting data.');
if ($result_2 = $sql_3) {
mysqli_data_seek($result_2, 0);
$row_1 = mysqli_fetch_row($result_2);
}
if ($result_3 = $sql_3) {
mysqli_data_seek($result_3, 1);
$row_2 = mysqli_fetch_row($result_3);
}
?>
<form action="includes/checkbox.inc.php" method="post">
<input type="hidden" name="checkbox1" value="0">
<input type="checkbox" name="checkbox1" value="1"
<?php
if ($row_1[0]=="1") {
echo "checked";
} else {
echo " ";
}
?>
> Item 1<br>
<input type="hidden" name="checkbox2" value="0">
<input type="checkbox" name="checkbox2" value="1"
<?php
if ($row_2[0]=="1") {
echo "checked";
} else {
echo " ";
}
?>
> Item 2<br>
<input type="submit" name="Submit" value="Submit">
</form>
<br>
Reset
<br>
<?php
mysqli_close($conn);
?>
</body>
</html>

How to retrieve values from SQLite 3 database on the basis of multiple check boxes selected at once in PHP?

I am new to PHP coding. I have different preferences for the user to select from my html page. I want to retrieve all the check boxes selected by the user and display the hotel names which have all those preferences in them. For example if a user selects "Roof top", "Sea side" and "Swimming pool" check boxes, then the hotels against which their is a 1 placed in the respective columns in the mytrip.db database must be retrieved all at once and get displayed. My code takes only one checkbox value and displays the hotel name against that only. I want to display the hotels that contain all the preferences.
My code is below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<form action="php_checkbox.php" method="post">
<label class="heading">Select Your Preferences:</label>
<input type="checkbox" name="check_list[]" value="Swimming pool"><label>Swimming pool</label>
<input type="checkbox" name="check_list[]" value="Roof top"><label>Roof top</label>
<input type="checkbox" name="check_list[]" value="Sea side"><label>Sea side</label>
<input type="submit" name="submit" Value="Submit"/>
</html>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>
checkbox_value.php code is below:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
$prefarray=array();
$i=0;
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected) {
$prefarray[$i]= $selected;
echo "<p>".$prefarray[$i] ."</p>";
echo "<p>".$selected ."</p>";
$i++;
}
echo "<p>".$i ."</p>";
$sql =<<<EOF
SELECT hotel_name from Dubai WHERE $prefarray[i]==1 AND $prefarray[i-1]==1 ;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
}
else{
echo "<b>Please Select Atleast One Option.</b>";
}
}
?>
The problem with this code is that it only displays one checkbox value if I use query
SELECT hotel_name FROM Dubai WHERE $selected==1
I tried to save the check box values selected by making an array "prefarray". But when I execute the query that I have posted in my checkbox_value.php code it gives me error of "Undefined offset 3 in prefarray". I want the data base query to have only those checkbox values that have been selected by the user. For example if the user has selected 2 out of three checkboxes then my query should look like
SELECT hotel_name FROM Dubai WHERE $checkbox==1 AND $checkbox2==1;
Any help to achieve two of these tasks will be appreciated!
I have fixed and refactored (couldn't stop myself) your code.
I have changed column names to proper ones. There was some redundant code which did nothing so I got rid of it. The main thing you were looking for is concatenating each chosen column in foreach loop. I'm also checking selected values against hard coded $hotelOptions for protection against sql injection.
Here is what I got:
checkbox_value.php:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$hotelOptions = array('swimming_pool', 'roof_top', 'sea_side');
if (isset($_POST['submit'])) {
if (!empty($_POST['check_list']) && is_array($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
$where = '';
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
if (array_search($selected, $hotelOptions) !== false) {
$where .= " AND {$selected} = 1";
}
}
$where = substr($where, 5, strlen($where));
$sql = "SELECT hotel_name FROM Dubai WHERE {$where};";
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
} else {
echo "<b>Please Select Atleast One Option.</b>";
}
}
html layout:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css"/>
</head>
<body>
<div class="container">
<div class="main">
<form action="checkbox_value.php" method="post">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<p class="heading">Select Your Preferences:</p>
<input type="checkbox" name="check_list[]" value="swimming_pool" id="checkbox_1">
<label for="checkbox_1">Swimming pool</label>
<input type="checkbox" name="check_list[]" value="roof_top" id="checkbox_2">
<label for="checkbox_2">Roof top</label>
<input type="checkbox" name="check_list[]" value="sea_side" id="checkbox_3">
<label for="checkbox_3">Sea side</label>
<div>
<input type="submit" name="submit" Value="Submit"/>
</div>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>

PHP random number not working

I want to write a php code that displays a random image and the person has to guess what it is. The problem is my php code tells me that the right city is incorrect, i cant figure out why
<?php
$random = rand(1, 3);
$answer ;
if ($random == 1) { $answer = "chicago" ;}
elseif($random == 2) {$answer = "LA" ;}
elseif($random == 3) {$answer = "NewYork" ;}
else {echo "Answer is None" ; }
if (isset($_POST["choice"])) {
$a = $_POST["choice"];
if($a ==$answer){
echo "<br> working <br>" ;
}else {echo "<br> Not Working <br>";}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>City Guess</title>
</head>
<body>
<center>
<img src="four/Image_<?php echo $random ;?>.jpg" width="960" height="639" alt=""/>
<form action="" method="POST">
chicago <input type= "radio" name="choice" value="chicago" />
<br>
LA <input type= "radio" name="choice" value="LA" />
<br>
NewYork <input type= "radio" name="choice" value="NewYork" />
<br>
<input type ="submit" value="Submit" />
</form>
</center>
</body>
</html>
You're generating your random value EVERYTIME the page is loaded. e.g. when the person first visits it and gets the form, you generate 2. When the form is submitted, you generate ANOTHER value, and this time it's 3. So even though the user correctly answers 2, you say they're wrong because the you've forgotten what you originally asked.
You need to store the generated value somehow, and compare that to the response, e.g.
$rand = rand(1,3);
<input type="hidden" name="correct_answer" value="$rand">
if ($_SERVER["REQUEST_METHOD"] == 'POST') {
if ($_POST['correct_answer'] == $_POST['user_answer']) {
echo 'correct';
}
}
The problem is your logic, you do not store the generated number that is used to show the image, instead you generate a new number every time you open the page.
You should store the generated number in (for example...) a session to preserve it and use that to compare.
Try it:
$random = floor(rand(1, 4));
I hope it helps.
Add the following hidden field in your form, using value="<?php echo $answer ?>" and it will work with your present code.
<input type="hidden" name="correct_answer" value="<?php echo $answer ?>">
Matter 'o fact, you don't even need name="correct_answer"
Just do:
<input type="hidden" value="<?php echo $answer ?>">
Remember when you test this, you have a "1 in 3" chance for success!
Edit
Here's the code that I used:
<?php
$random = rand(1, 3);
$answer;
if ($random == 1) { $answer = "chicago" ;}
elseif($random == 2) {$answer = "LA" ;}
elseif($random == 3) {$answer = "NewYork" ;}
else {echo "Answer is None" ; }
if (isset($_POST["choice"])) {
$a = $_POST["choice"];
if($a ==$answer){
echo "<br> working <br>" ;
}else {echo "<br> Not Working <br>";}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>City Guess</title>
</head>
<body>
<center>
<img src="four/Image_<?php echo $random ;?>.jpg" width="960" height="639" alt=""/>
<form action="" method="POST">
<input type="hidden" value="<?php echo $answer ?>">
chicago <input type= "radio" name="choice" value="chicago" />
<br>
LA <input type= "radio" name="choice" value="LA" />
<br>
NewYork <input type= "radio" name="choice" value="NewYork" />
<br>
<input type ="submit" value="Submit" />
</form>
</center>
</body>
</html>

Populate dropdown box from array and display with php

I am trying to populate a dropdown box with contents of the color array then display in a php file. Also display radio button selection on php file. I can not figure it out. I havent even started with the display of the array in the php file because I cant even populate the dropdown box. Any help would be much appreciated.
My HTML file
<!DOCTYPE html>
<?php
$Color = array("Red", "Blue", "Green", "Cyan", "Magenta", "Yellow");
$Food = array("Barbeque", "Chinese", "Japanese", "Thai", "Steak", "Vegan", "Mexican");
?>
<html lang="en">
<head><title>Lab 08</title></head>
<body>
<h2>Data Collection</h2><p>
<form method="get" action="test.php">
<table>
<p>Select your favorite color.</p>
<select name=Color>
<?php
foreach($Color as $col)
{
echo "<option value=\"$col\">". $col ."</option>\n";
}
?>
</select>
<p>Select your favorite type of food.</p>
<input type="radio" name="Food" value="Barbeque">Barbeque<br>
<input type="radio" name="Food" value="Chinese">Chinese<br>
<input type="radio" name="Food" value="Japanese">Japanese<br>
<input type="radio" name="Food" value="Thai">Thai<br>
<input type="radio" name="Food" value="Steak">Steak<br>
<input type="radio" name="Food" value="Vegan">Vegan<br>
<input type="radio" name="Food" value="Mexican">Mexican<br>
<p></p>
<tr><td>Enter your first name:</td><td><input name="First" type="text" /></td></tr>
<tr><td>Enter your last name:</td><td><input name="Last" type="text" /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value ="Submit"/></td></tr>
</table>
</form>
</body>
</html>
My PHP file
<!DOCTYPE html>
<?php
$First = (isset($_GET['First']) ? $_GET['First'] : null);
$Last = (isset($_GET['Last']) ? $_GET['Last'] : null);
$Color = (isset($_GET['Color']) ? $_GET['Color'] : null);
$Food = (isset($_GET['Food']) ? $_GET['Food'] : null);
?>
<html>
<head>
<title>Lab 08</title>
</head>
<body>
<?php
if ($Color) {
echo "<p>$Color</p>";
}
else if (empty($Color)) {
echo "<p>Please enter your favorite color.</p>";
}
if ($Food) {
echo "<p>$Food</p>";
}
else if (empty($Food)) {
echo "<p>Please enter your favorite food.</p>";
}
if (!is_numeric($First) and (!empty($First))) {
echo "<p>$First</p>";
}
else if (empty($First)) {
echo "<p>Please enter first name.</p>";
}
else if (is_numeric($First)) {
echo "<p>First name must be letters.</p>";
}
if (!is_numeric($Last) and (!empty($Last))) {
echo "<p>$Last</p>";
}
else if (empty($Last)) {
echo "<p>Please enter last name.</p>";
}
try:
//$row = null;
while ($row = $col){
echo "<option value=\"$row\">". $row ."</option>\n";
}
You write in your comment, that
[...] The first is an HTML file and the second is a php file. [...]
You cannot run PHP code in a HTML file. Change the file extension of your first file from .html to .php to fix this.

In PHP how to output the contents of a radiobox array using POST?

I want to output the values of the checkbox in the same way I'm outputting the values from the text fields. Since the checkbox can have multiple inputs I'm using an array for that but trying to cycle through the array for values hasn't worked for me.
tried foreach($type as $item) and echoing $item within the HTML like it says in the PHP book I have but that hasn't worked.
How should I do and where should the code be? I'm also unable to use PHP within the HTML for some reason, I'm not sure why that is or if its something to do with the echo<<<_END or not. Help appreciated.
<?php // formtest.php
if (isset($_POST['game'])) $game = $_POST['game'];
else $game = "(Not entered)";
if (isset($_POST['genre'])) $genre = $_POST['genre'];
else $genre = "(Not entered)";
if (isset($_POST['type'])) $type = $_POST['type'];
else $type = "(Not entered)";
echo <<<_END
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: $game in the $genre genre and of the type<br />
<form method="post" action="formtest.php">
What is your game?
<input type="text" name="game" />
<br />
What is your genre?
<input type="text" name="genre" />
<br />
Type?
Retail <input type="checkbox" name="type[]" value="Retail" />
Downloadable <input type="checkbox" name="type[]" value="Downloadable" />
Free <input type="checkbox" name="type[]" value="Free" />
<br />
<input type="submit" />
</form>
</body>
</html>
_END;
?>
With the form as it is now, $_POST['type'] will be an array since it's using checkboxes (and named appropriately), not radios. Here I just implode it for display, but you can loop through it like any array. It should be worth noting that any time you're wondering what a form is giving you, you can var_dump($_POST) or var_dump($_GET) depending on where the data is coming from. It helps a lot with debugging.
Here's what I got, I switched from heredoc, but your heredoc should work fine if you add $type back in somewhere, I didn't notice it in the original code:
<?php // formtest.php
if (isset($_POST['game'])) $game = $_POST['game'];
else $game = "(Not entered)";
if (isset($_POST['genre'])) $genre = $_POST['genre']; //Edit: Fixed line, oops
else $genre = "(Not entered)";
if (isset($_POST['type'])) $type = implode(', ',$_POST['type']);
else $type = "(Not entered)";
//Normally I'd specify a charset, but for simplicity's sake I won't here.
$type = htmlspecialchars($type);
$game = htmlspecialchars($game);
$genre = htmlspecialchars($genre);
?>
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: <?php echo $game; ?> in
the <?php echo $genre; ?> genre and of the type <?php echo $type; ?><br />
<form method="post" action="">
What is your game?
<input type="text" name="game" />
<br />
What is your genre?
<input type="text" name="genre" />
<br />
Type?
Retail <input type="checkbox" name="type[]" value="Retail" />
Downloadable <input type="checkbox" name="type[]" value="Downloadable" />
Free <input type="checkbox" name="type[]" value="Free" />
<br />
<input type="submit" />
</form>
</body>
</html>
Addendum:
If you switched and used radios like
<input type="radio" name="type" value="Downloadable" />
$_POST['type'] would be a simple string since you can only select one of the set.
To the file you post it the type[] will be saved as an array. For example
$a=$_POST['type'];
Although I don't find any point in doing this to radio-buttons, because their purpose is to pass only 1 value(unless you want specifically to).
Ok, first you don't need to echo the entire html output. Second your questions says radio buttons, but the html shows checkboxes. A radio field will only produce one result so you don't need [] after then name. Checkboxes will return an array when named with a []. So if you are using checkboxes you will need to process the result as an array. If you change the field to radio it should work fine.
<?php // formtest.php
if (isset($_POST['game'])) {
$game = $_POST['game'];
}
else { $game = "(Not entered)"; }
if (isset($_POST['genre'])) {
$genre = $_POST['genre'];
}
else { $genre = "(Not entered)"; }
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
else { $type = "(Not entered)"; }
?>
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your game is: <?php echo $game; ?> in the <?php echo $genre; ?> genre and of the type <?php echo $type; ?><br />
<form method="post" action="test.php">
What is your game?
<input type="text" name="game" <?php if ($game != "(Not entered)") { echo "value='" . $game . "'"; } ?> />
<br />
What is your genre?
<input type="text" name="genre" <?php if ($genre != "(Not entered)") { echo "value='" . $genre . "'"; } ?> />
<br />
Type?
Retail <input type="radio" name="type" value="Retail" <?php if ($type == "Retail") { echo "checked"; } ?> />
Downloadable <input type="radio" name="type" value="Downloadable" <?php if ($type == "Downloadable") { echo "checked"; } ?> />
Free <input type="radio" name="type" value="Free" <?php if ($type == "Free") { echo "checked"; } ?> />
<br />
<input type="submit" />
</form>
</body>
</html>

Categories