how do i clear the screen of a calculator in php - php

i'm trying to find a way to erase the text screen from my calculator when you press the +/- button so it acts more like a real calculator.
i'm pretty new to php (a week or two) so i'm still learning but i cant figure this out.
the php file returns html code where in i have a <input type='text' named result value='$value'>
(calculator screen).
and a series of submit buttons with a name and value of 1,2,3,+,...
when i press a button a char gets added to the string in result.
when i press on the '=' button it reads the string with eval();
and calculates it.
iv'e tried with a function but i cant figure it out some ideas or tips would be very much welcome.
$value = '';
if(isset($_GET['result']))
$value.=$_GET['result'];
if(isset($_GET['1']))
$value .='1';
if(isset($_GET['2']))
$value .='2';
//and so on ...
if(isset($_GET['+']))
$value .='+';
if(isset($_GET['-']))
$value .='-';
if(isset($_GET['='])){
eval('$result = '.$value.';');
$value = $result;}
return "<form action='index.php' method='get'>
<br><input type='text' name='result' value='$value'><br>
<input type='submit' name='1' value='1'>
<input type='submit' name='2' value='2'>
//and so on ...
(the rest of the html code is loaded somewhere else)

This PHP code below will execute JavaScript code to clean the input field,
echo"<script>document.getElementsByName('result')[0].value = '';</script>
This should resolve your question but i have to tell you that PHP isn't suitable choice to make a web calculator, You need to use JavaScript to make a real calculator without refreshing the page.
Please copy this code below to an HTML file and try it so you can get an idea how it works.
First Number
<input type="text" id="firstNumber" value="6" /><br>
Second Number
<input type="text" id="secondNumber" value="5" /><br>
Result
<input type="text" id="result" /><br>
<button type="button" onclick="Calculate();">Calculate</button>
<script>
function Calculate(){
let firstNumber;
let secondNumber;
firstNumber = document.getElementById("firstNumber").value;
secondNumber = document.getElementById("secondNumber").value;
document.getElementById("result").value = Number(firstNumber) + Number(secondNumber);
// "Number" is to tell javascript its a number not a string/text,
// without "Number" it will concat both numbers
}
</script>

You should use brackets for your conditions, especially if you nest them:
if(isset($_GET['result'])) {
$value .= $_GET['result'];
}
And your indentation makes it look like Python, someone reading it would mistake it for a condition nested in another condition and believe that your if(isset($_GET['2'])) is true only if if(isset($_GET['1'])) is also true.
A switch is a better solution here (and even better for the operators since you probably only have four of them), but in any case, you should assign each term of your operation in a single variable.

Related

Is there a way to send only relevant data when a form has multiple similar fields?

I'm trying to recreate a "commentary section" on my project. I have a loop to display many "posts" and each post has it's own comment section, all inside the same Form. because of that I end up having multiple fields with similar names (i.e button1, button2, button3, etc etc etc, one for each post). Is it possible to have one isset($post['button']) that fits all and only brings the info related to the one I clicked?
I could have each post be a separate Form but then I would have do re-do a good portion of what I did so far. I was hoping there's a way around it
that's what I have:
input type='text' name='post_comment".$k."' class='form-control' value=''
input type='submit' class='btn' name='postComment".$k."' value='Comment'
...
if(isset($post['postComment'])){
//do something
}
If I hardcode $k into my isset (i.e isset($post['postComment34'])) everything works as I wanted. Is it possible to have my isset accept any 'postCommentxx'?
You really need to use an array with matching indexes:
<input type='text' name='post_comment[$k]' . . .
<input type='submit' name='postComment[$k]' . . .
Then you can use the index of the submit to get the text:
if(isset($post['postComment'])){
$key = key($_POST['postComment']);
$text = $_POST['post_comment'][$key];
}
I would change postComment to something like submit as it is confusing to have variables of the same name just slightly different.
Welcome to Stackoverflow!
So, if I understand your question right, you want to just use 1 form and not using multiple forms for sending comments on posts. Try using <button type='submit'> instead of <input type='submit>'. Look at my example:
<input type='text' name='post_comment".$k."' class='form-control' value=''>
<button type='submit' class='btn' name='postComment' value='".$k."'>Comment</button>
Now you can go on with your php code;
if (isset($_POST['postComment'])) {
$postid = $_POST['postComment'];
$comment = $_POST['post_comment'.$postid];
// Do something
}
That's it! (I hope I helped you :P)

Return value from element while showing another

Hi lets say I'm showing a numeric value in an element (not sure what element to use), what i want to achieve is once the numeric value is clicked (Thinking of onclick="this.form.submit();" or submit button) it will submit different designated value from the numeric value let us say. Apple then my sql query would retrieve apple and use it. NOTE: I have multiple numeric values and multiple designated values for each numeric value as an example it looks like this:
(numeric value) = (designated value)
15123 = apple
24151 = orange
39134 = peach
Here so far is what i have.
<input type='submit' name='searchthem' placeholder='<?php echo $numeric_value; ?>'
value='apple'>
** NOTE i have multiple numeric values with different designated value
And this is the SQL in the same page:
SELECT * from tbl_fruits where fruit_name='".$_POST['searchthem']."' ;
Would appreciate some help and ideas, If there is confusion please comment so i may further clarify.
Use select element and just submit the form so that it can process the values. if you wish to use AJAX, use some javascript and output the result in the browser.
If I understand your problem correctly you should add an array for the definition terms and do it like this:
<input type="hidden" name="searchterm" value="<?php echo $numeric_value; ?>" />
<input type='submit' name='send' value="<?php echo $names[$numeric_value]; ?>" />
Then in PHP switch through the values:
switch($_POST['searchterm']){
case(15123) $term = 'apple';break;
case(24151) $term = 'ornage';break;
case(39134) $term = 'peach';break;
}
This will secure your SQL query, too. [Beware: Never use unfiltered input (i.e. $_POST in your example) from the browser in SQL queries!]

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

Javascript mysql interface?

I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed

Prevent empty form input array from being posted?

Sorry if this has been answered somewhere; I'm not quite sure how to phrase the problem to even look for help.
Anyway, I have a form with three text input boxes, where the user will input three song titles. I have simple PHP set up to treat those input boxes as an array (because I may want, say, 100 song titles in the future) and write the song titles to another document.
<form method="post">
<input type="text" name="songs[]" value="" />
<input type="text" name="songs[]" value="" />
<input type="text" name="songs[]" value="" />
<button type="submit" name="submit" value="submit">Submit</button>
</form>
<?php
if (isset($_POST['submit'])) {
$open = fopen("test.html", "w");
if(empty($_POST['songs'])) { }
else {
$songs = $_POST['songs'];
foreach($songs as $song) {
fwrite($open, $song."<br />");
};
};
};
?>
This correctly writes the song titles to an external file. However, even when the input boxes are empty, the external file will still be written to (just with the <br />'s). I'd assumed that the if statement would ensure nothing would happen if the boxes were blank, but that's obviously not the case.
I guess the array's not really empty like I thought it was, but I'm not really sure what implications that comes with. Any idea what I'm doing wrong?
(And again, I am clueless when it comes to PHP, so forgive me if this has been answered a million times before, if I described it horribly, etc.)
you should check each entry:
<?php
if (isset($_POST['submit'])) {
$open = fopen("test.html", "w");
foreach($_POST['songs'] as $song) {
if(!empty($song)) {
fwrite($open, $song."<br />");
};
};
};
?>
Indeed $_POST['songs'] is not an empty array, it's an array of 3 empty strings.
You can use the following to clear out all the empty values:
$song_titles = array_filter($_POST['songs'], function($title) {return (bool) trim($title);});
You could also put some other checks into that callback function (whitelist only alphanumerics and some other characters (spaces, dashes etc)).
If you have a version of PHP older than 5.3 you'll have to define the callback function separately, see http://us2.php.net/manual/en/function.array-filter.php

Categories