Display result in same field that had user input [PHP] - php

Hello I have a simple page that allows a user to enter a binary value which is then converted into a decimal value. However, I am using two fields, one for entering the binary value, and the other to display the result in decimal.
I want to only use on field, so when the user enters the binary value, the result in decimal will appear in the same box that they entered input. Here is my current code:
<?php
if (isset($_POST['submit']))
{
$str = $_POST['binToDec'];
$pos = 0;
$sum = 0;
$tempSum = 0;
$strLength = strlen($_POST['binToDec']) - 1;
$powerOfTwo = 1;
if ( $str{strLength} == 1 )
$sum += 1;
for ( $i = $strLength - 1; $i >=0; $i-- )
{
$tempSum = ($powerOfTwo *= 2);
if ( $str{$i} == 1 )
$sum += $tempSum;
}
}
?>
<html><body>
<form method="post" action="#">Binary value: <input name="binToDec"><br />
Result: <input value="<?php if (isset($sum)) echo $sum ?>"><br />
<input type="submit" name="submit" value="Convert">
</form>
<body></html>

This this little modification will solve your issue:
<form method="post" action="#">
Binary value: <input name="binToDec" value="<?php if (isset($sum)) echo $sum ?>"><br />
<input type="submit" name="submit" value="Convert">
</form>
This code is setting value on the input you've used for the POST action of the form.

Here's the code:
<?php
if (isset($_POST['submit']))
{
$str = $_POST['binToDec'];
$pos = 0;
$sum = 0;
$tempSum = 0;
$strLength = strlen($_POST['binToDec']) - 1;
$powerOfTwo = 1;
if ( $str{strLength} == 1 )
$sum += 1;
for ( $i = $strLength - 1; $i >=0; $i-- )
{
$tempSum = ($powerOfTwo *= 2);
if ( $str{$i} == 1 )
$sum += $tempSum;
}
}
?>
<html><body>
<form method="post" action="#">
Binary value: <input name="binToDec" value="<?php if (isset($sum)) echo $sum ?>" />
<input type="submit" name="submit" value="Convert">
</form>
<body></html>

Try to use the onkeyup or onkeydown or onchange to show the value in the same box, using
javascript,
example,
function Conversion(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
Enter: <input id="bin" name="" type="text" onkeyup="Conversion(this)" size=20>
Store return value to the same text box using the javascript like by using document.getElementbyId

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>

Why can I not use filter_input to get information from a form where $_get works just fine

I am using get method with a form in order to store information of checkboxes status into an array
I have attempted to use a filter_input line to take information from each checkbox sequentially and store it into an array, everything works just fine when replaced with $_get instead, but I have been told not to use $_get for the sake of security.
<form action="" method="get">
<input type="checkbox" name="1">Show Name<br>
<input type="checkbox" name="2">Show Category<br>
<input type="checkbox" name="3">Show Type<br>
<input type="submit" value="Submit">
</form>
<?php
$formArray = array();
$x = 1;
while ($x < 4) {
if (isset($_GET[$x])) {
$formArray[$x] = filter_input(INPUT_GET, "$x", FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH)
}
else {
$formArray[$x] = "off";
}
$x = $x + 1;
}
?>
The array should then store the values of "on" or "off" but it is just left blank, as I have mentioned when replaced with "$formArray[$x] = $_GET["$x"];", The program functions 100% correctly
You are misusing filter_input,
core implementation of filter_input is as follows,
$b = isset($_GET['b']) && is_string($_GET['b']) ? $_GET['b'] : '';
Name of your element is an integer. So filter_input will return false if name is not string and null if name is not set.
I have modified your snippet to make it work,
<form action="" method="get">
<input type="checkbox" name="t1">Show Name<br>
<input type="checkbox" name="t2">Show Category<br>
<input type="checkbox" name="t3">Show Type<br>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_GET)) {
$formArray = [];
$x = 1;
while ($x < 4) {
if (isset($_GET['t' . $x])) {
$formArray[$x] = filter_input(INPUT_GET, 't' . $x, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
} else {
$formArray[$x] = "off";
}
$x = $x + 1;
}
echo "<pre>";
print_r($formArray);
die;
}
?>
If 2 is checked,
Output:-
Array
(
[1] => off
[2] => on
[3] => off
)
And the filter flags you are using are for the data element is carrying.
By doc.

php code for find largest and second largest number without using array

<form id="form1" name="form1" method="post" action="">
<input name="txt1" type="text" /><br />
<input name="txt2" type="text" /><br />
<input name="txt3" type="text" /><br />
<input name="s" type="submit" value="Find No"/>
</form>
Here is my html code.
<?php
$a = 10;
$b = 25;
$c = 20;
if($a > $b)
{
if($a > $c)
{
echo "a is biggest number";
}
else
{
echo "c is biggest number";
}
}
if($b > $c)
{
echo "b is biggest number";
}
?>
` Here is the code for finding
largest among three no.s . I wish to get largest and second largest no
Given an array of numerical strings obtained from the input fields, for example one that mirrors your original values:
$a = array('1', '5', '19', '200', '999');
you can convert it into a true numerical array using the following approach:
$a = array_map('intval', $a);
and then proceed exactly as you did before:
$last = max($a);
$second = max(array_diff($a,[$last]));
Fiddle here.
you have to use input box for this and a submit button for very simple basic working model.
HTML:
<form action="/path to your php file or leave blank if both html and php are in same file">
<input type="text" name="arr" value=''>
<input type="submit" name="submit" value="submit">
</form>
// now user can provide input with space in input box such as 9 11 13 15 16 29 etc.
PHP
<?php
if(isset($_REQUEST['arr']) && !empty($_REQUEST['arr'])){
$a = explode(' ', $_REQUEST['arr']);
$last = max($a);
$second = max(array_diff($a,[$last]));
echo $second;
echo $last;
?>
I think this will resolve your query.
Here we use reverse array sort with largest and second largest number
$result = array(1,5,19,200,999);
$count = count($result);
for($i=0;$i<$count;$i++){
for($j=$i+1;$j<$count;$j++){
if($result[$i]<$result[$j]){
$m = $result[$i];
$result[$i] = $result[$j];
$result[$j] = $m;
}
}
}
echo "Largest Number : ".(!empty($result[0])?$result[0]:FALSE)." Largest Second Number : ".(!empty($result[1])?$result[1]:FALSE);

php word check if they are the same

I need that they check my word witch i written in text field. If 2 words the same i should get message - "They are the same".
<?php
function array_random($arr, $num = 1) {
shuffle($arr);
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[] = $arr[$i];
}
return $num == 1 ? $r[0] : $r;
}
$a = array("snow", "ball", "side");
//print_r(array_random($a));
//print_r(array_random($a, 3));
?>
<form name='form' method='post' align = "center">
<?php
$zod = (array_random($a)); echo $zod; ?> <input type="text" name="name" id="name" ><?php
if((isset($_POST['name'])) && !empty($_POST['name']))
{
$name = $_POST['name'];
echo ' '.$name;
}
?><br/><br>
<input name="select" type="submit" onclick="select()" value="select" />
</form>
A simple comparison uses the '==' operator. These can be used to compare something. You want to compare a posted value with the one from your array. which is random:
<?php
function array_random($arr, $num = 1) {
shuffle($arr);
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[] = $arr[$i];
}
return $num == 1 ? $r[0] : $r;
}
if ( isset ( $_POST['submit'] ) && isset ( $_POST['name'] ) ) {
if ( $_POST['compare'] == $_POST['name'] )
echo "They are the same, hurray!<br />";
else
echo "These don't match!";
}
$a = array ( "snow", "ball", "side" );
$rand = array_random ( $a );
?>
<form name='form' method='post' align = "center">
Please type the word: <?php echo $rand; ?>
<input type="text" name="name" id="name" >
<input type="hidden" name="compare" id="compare" value="<?php echo $rand ?>" >
<input name="submit" type="submit" onclick="select()" value="select" />
</form>
As you wanted, a random value is picked and compared to what the user posted.

Form not outputting number [duplicate]

This question already has an answer here:
Output of numbers are incorrect sometimes.
(1 answer)
Closed 9 years ago.
Given an input of an expression consisting of a string of letters and operators (plus sign, minus sign, and letters. IE: ‘b-d+e-f’) and a file with a set of variable/value pairs separated by commas (i.e: a=1,b=7,c=3,d=14) write a program that would output the result of the inputted expression.
For example, if the expression input was ("a + b+c -d") and the file input was ( a=1,b=7,c=3,d=14) the output would be -3.
Thus far I have got this, it calculates the numbers but not sure how to calculate it by the letters abcd,
<html>
<head>
</head>
<body>
<form action = "" method = "GET">
Number 1: <input type = "text" name = "input[]" size=3>
<br/>
Number 2: <input type = "text" name = "input[]" size=3> <br>
Number 3: <input type = "text" name = "input[]" size=3> <br>
Number 4: <input type = "text" name = "input[]" size=3> <br>
<input type="hidden" name="calc" value ="yes">
<input type = "submit" name = "Calculate"/>
</form>
</body>
</html>
<?php
print_r($_GET);
$myInputs = $_GET['input'];
print_r($myInputs);
$myArray = array();
$myArray['a'] = 5;
$myArray['b'] = 10 ;
$myArray['c'] = 15 ;
$myArray['d'] = 20 ;
echo $myArray[$_GET['a']] + $myArray[$_GET['b']] ;
/*
if ($_GET['calc'] == "yes")
{
$a = $_GET['a'];
$b = $_GET['b'];
$c = $_GET['c'];
$d = $_GET['d'];
$total = $a+$b+$c+$d;
print "Total is: $total <p>";
}
*/
?>
<?php
$expression = '';
$input = array( 'a' => 5,
'b' => 10,
'c' => 15,
'd' => 20);
$total = 0;
$sum = '';
// Override default expression and input values
if(isset($_POST['Calculate']))
{
$input = $_POST['input']; //input being passed via POST method
$expression = $_POST['expression']; //expression being passed via POST method
}
// make sure the users expression is safe to use
if(preg_match('#^[a-z+-\s]+$#i', $expression))
{
$sum = $expression; //evaluates sum as expression
$input_letters = array(); //puts letters into a array
$input_operators = array(); //puts operators into a array
for ($i = 0; $i < strlen($expression) ; $i++) { //gets string length
if (($i % 2) == 0) {
$input_letters[] = $expression[$i]; //getting the character for the position i
} else {
$input_operators[] = $expression[$i];
}
}
//
for ($i = 0 ; $i < sizeof($input_letters); $i++) { //size of= numbers (4)
$value = $input[$input_letters[$i]]; //takes the value from the letters
if ($i == 0) {
$sum += $value; //adds the sum if = 0
} else {
if ($input_operators[$i-1] == '+') { //checks to see if the operator is +
$sum += $value;
} else if ($input_operators[$i-1] == '-') { //checks to see if the operator is -
$sum -= $value;
}
}
print_r($value);
}
} else {
echo "Error: expression not correct form"; //error message
}
?>
<form action="" method="post"> <!--Form begins-->
Number A: <input type="text" name="input[a]" value="<?php echo $input['a']; ?>" size=3> <br/>
Number B: <input type="text" name="input[b]" value="<?php echo $input['b']; ?>" size=3> <br>
Number C: <input type="text" name="input[c]" value="<?php echo $input['c']; ?>" size=3> <br>
Number D: <input type="text" name="input[d]" value="<?php echo $input['d']; ?>" size=3> <br>
<br>
Expression: <input type = "text" name = "expression" value="<?php echo $expression ?>"> =
<?php echo $sum; ?><br>
Sum: <?php echo $sum; ?><br>
<input type="submit" name="Calculate" />
</form>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$( "form" ).submit(function( event ) {
var val_is_good=($('input[name="expression"]').val().length==4)?true:false;
if(!val_is_good){alert('Enter four letters or die!');}
});
</script>
Now I added a script to tell users if they enter more then 4 letters a alert message says please only enter four letters, would someone know why my script is outputing the alert message even when enter only four letters?
<html>
<head>
</head>
<body>
<form action = "" method = "GET">
Number 1: <input type = "text" name = "input[]" size=3>
<br/>
Number 2: <input type = "text" name = "input[]" size=3> <br>
Number 3: <input type = "text" name = "input[]" size=3> <br>
Number 4: <input type = "text" name = "input[]" size=3> <br>
<input type="hidden" name="calc" value ="yes">
<input type = "submit" name = "Calculate"/>
</form>
</body>
</html>
<?php
print_r($_GET);
$myInputs = $_GET['input'];
//you are assigning $_GET values to an array myInputs so no need here
print_r($myInputs);
echo $myInputs[0]+ $myInputs[1];
$myArray = array();
$myArray['a'] = 5;
$myArray['b'] = 10 ;
$myArray['c'] = 15 ;
$myArray['d'] = 20 ;
// In case of myarray it has keys a,b,c,d only... so need of using $_GET here also.
echo $myArray['a']+$myArray['b'];
// but if you want to it directly from$_GET values.
echo $_GET['input'][0]+ $_GET['input'][1];
?>
I found a solution at this site. Here is the code from that post:
<?php
$expression = '';
$input = array( 'a' => 5,
'b' => 10,
'c' => 15,
'd' => 20);
$total = 0;
$sum = '';
// Override default expression and input values
if(isset($_POST['Calculate']))
{
$input = $_POST['input'];
$expression = $_POST['expression'];
}
// make sure the users expression is safe to use
if(preg_match('#^[a-z+-\s]+$#i', $expression))
{
$sum = $expression;
$input_letters = array();
$input_operators = array();
for ($i = 0; $i < strlen($expression) ; $i++) {
if (($i % 2) == 0) {
$input_letters[] = $expression[$i];
} else {
$input_operators[] = $expression[$i];
}
}
//
for ($i = 0 ; $i < sizeof($input_letters); $i++) {
$value = $input[$input_letters[$i]];
if ($i == 0) {
$sum += $value;
} else {
if ($input_operators[$i-1] == '+') {
$sum += $value;
} else if ($input_operators[$i-1] == '-') {
$sum -= $value;
}
}
}
} else {
echo "Error: expression not correct form";
}
?>
<form action="" method="post">
Number A: <input type="text" name="input[a]" value="<?php echo $input['a']; ?>" size=3> <br/>
Number B: <input type="text" name="input[b]" value="<?php echo $input['b']; ?>" size=3> <br>
Number C: <input type="text" name="input[c]" value="<?php echo $input['c']; ?>" size=3> <br>
Number D: <input type="text" name="input[d]" value="<?php echo $input['d']; ?>" size=3> <br>
<br>
Expression: <input type = "text" name = "expression" value="<?php echo $expression ?>"> =
<?php echo $sum; ?><br>
Sum: <?php echo $sum; ?><br>
<input type="submit" name="Calculate" />
</form>

Categories