Creating checkboxes in HTML / PHP? - php

So I have the following code.
My main.html form lets me enter a value (a price for pc) and when I submit it calls the pcs.php script which displays all my pcs under the given value/price.
But I want to have an checkbox beside the information displayed by the script. ie
<br>alienware, 3000, gtx760 checkbox <br> asus rog, 2500, radeodhdxxxx checkbox <br>
and so on).
//main.html
<BODY>
<FORM METHOD="POST" ACTION="pcs.php" >
<INPUT TYPE='textbox' NAME='mypc' VALUE='' >
<INPUT TYPE="SUBMIT" NAME="Button" VALUE="Hit me">
</FORM> </BODY> </HTML>
//pcs.php
<?php
$dd = $_POST['mypc'];
$filename = "computer.txt";
$filepointer = fopen($filename,"r");
$myarray = file ($filename);
for ($mycount = 0; $mycount < count($myarray); $mycount++ )
{
$apc = $myarray[$mycount];
$price = getvalue($apc,1);
$part = explode(',', $apc);
//print $price ."<br>";
//print $str ."<br>";
if ($str <$dd )
{
for($pcount = 0; $pcount<3; $pcount++) {
print $part[$pcount] ."<br>";
}
print "<br>";
}
}
function getvalue ($text, $commaToLookFor)
{
$intoarray = explode(",",$text);
return $intoarray[ $commaToLookFor];
}
// fclose ($filepointer);
?>
<p>
</body>
</html>
// computer.txt file
alienware, 3000, gtx760<br>
asus rog, 2500, radeonhdxxx<br>
alienware, 5000, gtx titan<br>

In pcs.php you'll just need to modify your for loop to look something like:
// Create form
print '<form method="post" action="script_to_post_to.php">';
for ($mycount = 0; $mycount < count($myarray); $mycount++) {
$apc = $myarray[$mycount];
$price = getvalue($apc,1);
$part = explode(',', $apc);
if ($str < $dd) {
for($pcount = 0; $pcount<3; $pcount++) {
print $part[$pcount] ."<br>";
}
// Add checkbox and name with product type
print '<input type="checkbox" name="' . getvalue($apc, 2) . '" />';
print "<br>";
}
}
// Provide form submission button and close form element
print '<input type="submit" value="Submit" />';
print '</form>';
You'll have a form with each element having a checkbox and the ability to respond to the list of checked items in "script_to_post_to.php".

Related

how to make a button on a form work when clicked in php?

i have code like this
<body>
<form method = "POST">
<label for="">Star </label>
<input type="text" name = "star"></br>
<input type="submit" value= "Submit">
</form>
<?php
$Star = $Add = $Subs = NULL;
$Picture = "<img src = star.png>";
if($_SERVER['REQUEST_METHOD']=="POST"){
if(isset($_POST['star'])){
$Star = $_POST['star'];
for ($i=1; $i <= $Star + 1 ; $i++) {
echo "$Picture"; }
if(isset($_POST['Op'])){
$op = $_POST['Op'];
switch($op){
case 'ADD':
for ($i=1; $i <=$Star + 1 ; $i++) {
echo "$Picture";
}
case 'SUBS':
for ($i=1; $i <=$Star - 1 ; $i++) {
echo "$Picture";
}
}
}
}
?> <form method="POST">
<input type="submit" value="ADD" name = "Op"/>
<input type="submit" value="SUBS" name = "Op"/>
</form>
<?php } ?>
when I run it in the browser, the submit button works fine and displays a star image according to the input, but when the button is added and minus the star image doesn't increase and decrease. for example, if I input the number of 5 stars and I submit the program it works fine, after that when I click the add or subs button, the stars don't increase or decrease. sorry for my english
You have two forms in this code, first of all, combine both of them into a single form it looks way cleaner than this, and follow the below code it will help to achieve your task. ( Read comments in the code. )
<body>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>">
<label for="">Star </label>
<input type="text" name="star"></br>
<input type="submit" value="Submit" name="submit">
<input type="button" value="ADD" onclick="addNSub(this.value)" /> <!-- (this.value) will send the pressed button attribute value to the function -->
<input type="button" value="SUBS" onclick="addNSub(this.value)" />
</form>
<div id="starContainer">
<?php
$Star = $Add = $Subs = NULL;
$Picture = "<img src = 'star.png' class='starPng'>";
if (isset($_POST['submit'])) {
if (isset($_POST['star'])) {
$Star = $_POST['star'];
if (!empty($Star)) {
for ($i = 1; $i <= intval($Star); $i++) {
echo "$Picture";
}
}
}
}
?>
</div>
<script>
function addNSub(btnValue) {
const parentElement = document.getElementById("starContainer"); //get the star parent dive by it's id
const elements = document.querySelectorAll(".starPng"); //get all the star elements by it's class
if (btnValue == "ADD") { //if button value == ADD this code will execute
for (let i = 0; i <= elements.length; i++) {
if (elements.length == i) {
const getChild = elements[0]; //gets the first element (class ="starPng") under "starContainer" div
const cloneElement = getChild.cloneNode(true); // making clone of that element
parentElement.appendChild(cloneElement); //setting the clone to parent element ("starContainer" div)
}
}
} else if (btnValue == "SUBS") { //if button value == SUBS this code will execute
for (let i = 0; i <= elements.length; i++) {
if (elements.length == i) {
parentElement.removeChild(elements[0]); // removes the first HTML element (class ="starPng") under "starContainer" div
}
}
}
}
</script>
</body>

passing values from php to html

I want to pass values from my php code (in the same page) to my html - so I could print it out nicely
here is my php function (it's in a while cause it needs to print out 3 lines from a text)
if(sizeof($words)==1)
{
$single = new single;
$docres = $single->find($words);
$dir = "source";
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
echo fgets($handle);
//this is what i need to print in my html
$input = $_POST['input'];
$counter++;
}
}
}
}
and here is my html
<html>
<head>
<title>serach engine</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code' >
// <input type="value" name="input" value="<?php echo $input; ?>">
</center>
</form >
//I would like to print it out here
</div>
</body >
</html >
I searched over the web and saw a solution using $_POST but it didn't work for me...
You could just append it to a new variable and echo it out in the html.
For example:
while($counter < 3) {
echo fgets($handle);
//this is what i need to print in my html
$input .= $_POST['input'] . "<br />";
// You could also do:
// $input .= "<li>" . $_POST['input'] . "</li> "
// For a list item
$counter++;
}
And then echo it in the html:
</form>
<?php echo $input; ?>
</div>
Note: You did not increment your $counter in the while loop.

How to make a foreach loop show something for the first row, middle results, then a special last row result?

I was trying to display the results of this form where when you checkbox a fruit, it shows that fruit, then on the last one it puts a "." period instead of a comma.
It comes down to something in my foreach loop that is causing this.
<span style="font-family: arial,helvetica,sans-serif; font-size: 12px;"><?php
$fruitArray = array('orange', 'apple', 'grapefruit', 'banana', 'watermelon');
if(isset( $_POST['fruit']))
{ $values = array();
$i = 0;
$length = count($_POST['fruit']);
echo 'Checkbox checked: ';
foreach ($_POST['fruit'] as $selection) {
if ($i == 0) {
//first to show
echo $selection . ' , ';
} else if ($i == $length - 1) {
//last to show
echo $selection . '.';
}else{
echo $selection . ' , ';
$i++;
}
}
}
I also was trying this:
foreach ($_POST['fruit'] as $selection) {
echo reset($selection) . " , ";
echo current($selection) . " , ";
echo end($selection) . " . ";
}
?>
<html>
<head>
<title>Checkbox selection using PHP (using PDO) and MySQL v2</title>
</head>
<body>
<h2>Pick your most favourite fruits:</h2>
<form name="fruitcheckbox" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="checkbox" name="fruit[]" value="orange"> Orange
<input type="checkbox" name="fruit[]" value="apple"> Apple
<input type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit
<input type="checkbox" name="fruit[]" value="banana"> Banana
<input type="checkbox" name="fruit[]" value="watermelon"> Watermelon
<br>
<input type="submit" value="Save" name="btn_save">
</form>
</body>
</html> </span>
I added in here also if you only have 1 row, this is what you put in here:
$i = 0;
$length = count($_POST['fruit']);
//if one row
if ($length == '1'){
foreach ($_POST['fruit'] as $selection) {
echo 'Checkbox checked: '. $selection . '.';
echo 'Rows counted ' . $length;
}
}else{
echo 'Checkbox checked: ';
foreach ($_POST['fruit'] as $selection) {
echo $selection; //current fruit
if (each($_POST['fruit'])){
echo ", "; //current rows put a comma after fruit
}else if (!each($_POST['fruit'])) {
echo ".";//last row put period instead of comma
}
}
echo 'Rows counted ' . $length;
}

Compute 1st value on multiple values on a checkbox

I was trying to make a COMPUTERIZED ORDERING SYSTEM. My problem is how can I compute the 1st value on my checkbox. The second value on the checkbox will be posted on the summary of orders.
Once I've check all those three, it will compute the total amount of the menu and to display the selected menu on the summary of orders. But I can't figure out how can I display the total amount.
Can anybody guide me how to compute the total on my 1st value on the checkbox?
<form method="post">
<input name='ts[]' type='checkbox' value='40 |Tosilog'/> Tosilog
<br>
<input name='cs[]' type='checkbox' value='40 |Chiksilog'/>Chiksilog
<br>
<input name='ps[]' type='checkbox' value='45 |Porksilog'/>Porksilog
<br>
<input type="submit" name="go" value= "Total">
</form>
<?php
//tosilog
$ts = $_POST['ts'];
$value = explode("|",$ts[0]);
echo $value[0];
echo $value[1];
//chiksilog
$cs = $_POST['cs'];
$value = explode("|",$cs[0]);
echo $value[0];
echo $value[1];
//porksilog
$ps = $_POST['ps'];
$value = explode("|",$ps[0]);
echo $value[0];
echo $value[1];
?>
<!-- compute for the 1st value on checkbox -->
<?php
$ts=$_POST['ts[0]'];
$cs=$_POST['cs[0]'];
$ps=$_POST['ps[0]'];
?>
<?php $compute = $ts[0] + $cs[0] + $ps[0];?>
<?php echo "$compute " ; ?>
If you're getting an array of checkbox elements, and they are numeric, you can use array_sum(). Not sure I understand your suggested structure, but I'll give you a code sample here based on the existing form structure. Then I'll post another bit to try to make this simpler for you. Executive summary: You do not need all the variables that are created by this form structure.
<?php // RAY_temp_user193.php
error_reporting(E_ALL);
$total = 0;
$inputs = array();
$errors = array();
if (!empty($_POST))
{
if (!empty($_POST['ts']))
{
foreach ($_POST['ts'] as $ts)
{
$inputs[] = current(explode(' |', $ts));
}
}
else
{
$errors[] = 'Tosilog';
}
if (!empty($_POST['cs']))
{
foreach ($_POST['cs'] as $cs)
{
$inputs[] = current(explode(' |', $cs));
}
}
else
{
$errors[] = 'Chiksilog';
}
if (!empty($_POST['ps']))
{
foreach ($_POST['ps'] as $ps)
{
$inputs[] = current(explode(' |', $ps));
}
}
else
{
$errors[] = 'Porksilog';
}
// IF ERRORS
if (!empty($errors))
{
echo 'UNABLE TO PRINT COMPLETE TOTAL. MISSING: ' . implode(',', $errors);
}
$total = array_sum($inputs);
if ($total) echo "<br/>TOTAL: $total <br/>" . PHP_EOL;
// END OF THE ACTION SCRIPT
}
// CREATE THE FORM
$form = <<<ENDFORM
<form method="post">
<input name='ts[]' type='checkbox' value='40 |Tosilog'/> Tosilog
<br>
<input name='cs[]' type='checkbox' value='40 |Chiksilog'/>Chiksilog
<br>
<input name='ps[]' type='checkbox' value='45 |Porksilog'/>Porksilog
<br>
<input type="submit" value= "Total">
</form>
ENDFORM;
echo $form;
See http://www.laprbass.com/RAY_temp_miggy.php
This is probably more along the lines of the way I would do it. The script knows what goes into the HTML and it knows exactly what to expect in the POST request. It is easy to add or remove different inputs. Often these kinds of inputs come from a data base table.
<?php // RAY_temp_miggy.php
error_reporting(E_ALL);
$total = 0;
// EXPECTED INPUTS
$inputs = array
( 'Tosilog' => 40
, 'Chiksilog' => 40
, 'Porksilog' => 45
)
;
if (!empty($_POST))
{
// ACTIVATE THIS TO SEE WHAT WAS SUBMITTED
// var_dump($_POST);
// SUM OF THE ELEMENTS
$total = array_sum($_POST);
echo "TOTAL: $total";
// SUM OF THE EXPECTED INPUTS
$expect = array_sum($inputs);
if ($total != $expect) echo " BUT THERE MAY BE INCOMPLETE INPUTS!";
// END OF THE ACTION SCRIPT
}
// CREATE THE FORM
$checkboxes = NULL;
foreach ($inputs as $name => $value)
{
$checkboxes
.= '<input name="'
. $name
. '" type="checkbox" value="'
. $value
. '" />'
. $name
. '<br/>'
. PHP_EOL
;
}
$form = <<<ENDFORM
<form method="post">
$checkboxes
<input type="submit" value= "Total">
</form>
ENDFORM;
echo $form;

HTML form multiple fields

I have html form that looks like:
<form method="post" action="?a=up">
...some mysql query...
while ($i = mysql_fetch_array($result)) {
<input name="name[]" type="text" value="<?=$i['name'];?>" />
<input name="years[]" type="text" value="<?=abs($age);?>"/>
<input name="to[]" type="checkbox" value="<?=$i['id'];?>" />
}
<input name="" type="submit" value="go" />
</form>
The problem I have is that I can not get the values of the form fields such as "name" and "years".
I can only get a list of the ids (value of "to" checkbox).
The php code looks like:
$cnt = 0;
for($p = 0; $p <= (sizeof($to)-1); $p++)
{
echo $to[$p].$name[$p].$years[$p]"<br>";
$cnt++;
}
$tm = array($cnt);
What I'm doing wrong?
You're expecting a checkbox to be a successful control even if it isn't checked (and the specification says that it must not be so).
You should probably do something along the lines of:
<input name="name[<?php echo htmlspecialchars($i['id']); ?>]"
value="<?php echo htmlspecialchars($i['name']); ?>" />
<input name="years[<?php echo htmlspecialchars($i['id']); ?>]"
value="<?php echo abs($age);?>"/>
Update
Here is how you can get checkboxes that are checked using isset:
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
$cnt = 0;
for($p = 0; $p <= (sizeof($_POST['to'])-1); $p++)
{
if (isset($_POST['to'][$p]))
{
echo $_POST['to'][$p] . $_POST['name'][$p] . $_POST['years'][$p] . "<br>";
$cnt++;
}
}
$tm = array($cnt);
}
You are not getting the fields from POST array, here is how your code should be:
$cnt = 0;
for($p = 0; $p <= (sizeof($_POST['to'])-1); $p++)
{
echo $_POST['to'][$p] . $_POST['name'][$p] . $_POST['years'][$p] . "<br>";
$cnt++;
}
$tm = array($cnt);
Make sure that above code executes when form is submitted by putting it in this condition:
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
$cnt = 0;
for($p = 0; $p <= (sizeof($_POST['to'])-1); $p++)
{
echo $_POST['to'][$p] . $_POST['name'][$p] . $_POST['years'][$p] . "<br>";
$cnt++;
}
$tm = array($cnt);
}
And finally a little suggestion that you should avoid using short php tags <?=?> for they have posed security issues and can easily be embedded into images or xml. (Make sure that they are also turned on from php.ini if you want to use them)
Why dont you just try
$cnt = 0;
foreach ( $_POST['to'] as $k => $to ){
echo $_POST['to'][$k] . $_POST['name'][$k] . $_POST['years'][$k] . "<br />";
$cnt ++;
}
$tm = array ($cnt);

Categories