PHP calculator increase - php

I am creating simple calculator. I am just learning php and this is a small project.I have created a calculator with two inputs but I am now testing it with just one. It works but only if you type number+number. It doesn't work if it is number+number+number.
I would like that it would work if you inputted 2+2+2... or 2*2*2... or 6-2-2... and 2/2/2...
Code:
// Create Variables
$y = $_POST["input1"];
// Echo input value on screen
echo "<p>Operation: " . $y . "</p>";
// Validation
if(empty($y)){
?>
<script>
$(document).ready(function(){
$('#error').append('Error: Your Input is empty');
});
</script>
<?php
}elseif(preg_match("/[a-zA-Z]/", $y)){
?>
<script>
$(document).ready(function(){
$('#error').append('Error: You can only input numbers');
});
</script>
<?php
}else{
// Calculation Brain FOR + Operator
if (strpos($y,'+') !== false) {
$omega = substr($y, 0, strpos($y, '+'));
$alpha = substr($y, strpos($y, '+') + 1);
echo "<p>Omega: " . $omega . "</p>";
echo "<p>Alpha: " . $alpha . "</p>";
$gamma = $omega + $alpha;
// The Sum FOR + operator
echo "Calculation: " . $gamma;
}
}

That's usually a bad practice, but here you can use eval. But you have first to check that your string doesn't contains disallowed characters.
$allowedCharacters = "0123456789./*-+()% ";
if(preg_match('/^[^'.preg_quote($allowedCharacters).']+$/'), $y) {
eval('$result = '.$y.';');
echo "Calculation: " . $result;
}
The only problem is that you'll not be able to handle errors.

you could use this for the same operation
$test='2+2*3';
eval('$calc = '.$test.';');
echo "Calculation: " . $calc;
the out should be : 8

Related

How to echo/print within a fuction with undefined variables in php?

I am not the best at php but currently I am trying to learn. I can print fine outside of the function but the specific instructions I have been given require me to print the results within the function. I have tried
echo "$area";
echo "calculatearea ()";
ive searched but still cant figure out how to get a print within the function only outside of it.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
return $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
echo "Your rectangle circumference is: " . calculateCircumference() . '<br />' . "Your rectangle area is: " . calculateArea();
}
?>
<!---------------- Form---------------->
<div class="form">
<h3></h3>
<form action="PHP-sida4.php" method="POST">
<p>Length: <input type="text" name="Length"value=""></p>
<p>Width: <input type="text" name="Width"value=""></p>
<input type="submit" name="CalcBT" value="Calculate">
</form>
I need the return value of $area along with what I echo'd in the bottom to actually print within the first function ( calculateCircumference )
You can echo anything you want within the function but it won't show up until you call the function.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
// return $circ;
echo "Your rectangle circumference is: " . $circ . '<br />' . "Your rectangle area is: " . calculateArea();
return;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
calculateCircumference();
}
?>
I hope this helps!
Okay if am getting your question right, to need to return the area and some other text along with the area.
Let's begin with some house cleaning, therefore the $area global variable could be renamed to something else like $results Which will be an array or object. Taking it simple.
Lets go with an associative array where e.g:
$results = [
'area' => null,
'text' = null
];
From that your will be updating $results['area'] from the calculate function and also update the $results['text'] before calling echo, so probably extract the echoed text to another variable.
And now you can access $results anywhere within the file with both the area and the text:
To just be more expressive under CalculateArea() function do something like:
$results['area'] = $area;
Same thing with the echoed text.
You can use echo instead of return in your functions. To call them, your can just use function(); without any additional keyword :
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
echo $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
echo $area;
}
echo "Your rectangle circumference is: " ;
calculateCircumference() ;
echo '<br />' ;
echo "Your rectangle area is: " ;
calculateArea();
You can echo anything anywhere, be it inside a function or outside of it. If an echo is not performing, then there was either an error, or the line where the echo can be found was not executed.
In our case you have removed the echo after your functions, which, coincidentally happened to be the only place where they were called.

Using PHP to print to HTML5 output tag

I am new to this. If I have some PHP code as in the example below, I can use the echo function to print the result. Echo always prints at the top of the screen. How do I format the tag so that in this case the result "$myPi" is printed to the screen using an HTML5 output tag? I am a newbie so please be kind to me and don't flame my post - I tried to format the code. Thanks QJB.
function taylorSeriesPi($Iteration)
{
$count = 0;
$myPi = 0.0;
for ($count=0; ($count<$Iteration);$count++)
{
if ( ($count%4) == 1)
{
$myPi = $myPi + (1/$count);
}
if ( ($count%4) == 3)
{
$myPi = $myPi - (1/$count);
}
}
$myPi *= 4.0;
echo ("Pi is ". $myPi. " After ".$Iteration. " iterations");
}
You can insert PHP anywhere in your document, and reference functions from any other place within the document or included files.
For example:
<?php
function taylorSeriesPi($Iteration)
{
$count = 0;
$myPi = 0.0;
for ($count=0; ($count<$Iteration);$count++)
{
...
}
$myPi *= 4.0;
// Return the value so we can use this function later.
return $myPi;
}
?>
<html>
<body>
<div id="somediv">
<?php
$iteration = 6/*or whatever*/;
echo "Pi is " . taylorSeriesPi($iteration) . " After " . $iteration . " iterations";
?>
</div>
</body>
</html>
This will put the returned value and associated string within the <div> tag, but you can put it anywhere in your HTML, as the output of the echo will simply be text by the time the markup is seen by your browser.

jquery.load("something.php") not working well

i have a something.php which will print the option of dropdownlist,\
then i load the .php file with
$("#dropdownlist").load("something.php");
after i load, the output is displayed, but when i change the selected value, in debug mode i din not saw a selected="selected" on the option of dropdownlist and i cannot set a selectedvalue to the dropdownlist also with
$("#dropdownlist").val("2");
any one know why this happen and how can i solve it?
add-on code
--print option on .php--
while (isset($StatusArr[$loopCount])) {
if ($loopCount == 0) {
$selected = "selected='true'";
} else {
$selected = "";
}
echo "<option value='"
. $StatusArr[$loopCount][0]
. "' "
. $selected
. " >"
. $StatusArr[$loopCount][1]
. "</option>";
$loopCount ++;
}
---call in .js----
$('#select').load("../something.php", function (respond, fstatus, xhr) {
if (fstatus === "success") {
if (status !== "missing") {
$('#status').prop("selectedIndex", 3);
}
} else {
alert("Load data " + fstatus + "\n" + xhr.status + " " + xhr.statusText);
}
});
$("#dropdownlist").prop("selectedIndex", 1);
This jQuery code sets the selected option of the dropdownlist to the 2nd option.

jquery add to array then submit and pass data not working

My problem is:
I'm trying to submit an array of hidden input types, which are stacked into an array using jquery onclick, to a PHP file. However, when I try to count or even echo the passed variable in the php file (saveTest.php), no data appears or the count variable is zero.
I've searched and I found this guy's question:
pass an array from jQuery to PHP (and actually go to the page after submit)
I think I'm close to the above post but I'm still a newbie in jQuery so I don't understand much of the codes.
This is my jquery:
$(function(){
$("td").click(function(){
if($(this).hasClass("on"))
{
alert("Already marked absent");
}
else
{
$(this).addClass("on");
var currentCellText = $(this).text();
$("#collect").append("<input type='text' hidden = '" + currentCellText + "'/>" + currentCellText);
}
});
$("#clicky").click(function(){
$("td").removeClass("on");
$("#collect").text('');
$("#collect").append("Absentees: <br>")
});
});
<?php
session_start();
include 'connectdb.php';
$classID = $_SESSION['csID'];
$classQry = "SELECT e.csID, c.subjCode, c.section, b.subj_name, e.studentID, CONCAT(s.lname, ', ' , s.fname)name
FROM ENROLLMENT e, CLASS_SCHEDULE c, STUDENT s, SUBJECT b
WHERE e.csID = c.csID
AND c.csID = '" . $classID . "'
AND c.subjCode = b.subjCode
AND e.studentID = s.studentID
ORDER BY e.sort;";
$doClassQry = mysql_query($classQry);
echo "<table id='tableone'>";
while($x = mysql_fetch_array($doClassQry))
{
$subject = $x['subj_name'];
$subjCode = $x['subjCode'];
$section = $x['section'];
$studentArr[] = $x['name'];
$studentID[] = $x['studentID'];
}
echo "<thead>";
echo "<tr><th colspan = 7>" . "This is your class: " . $subjCode . " " . $section . " : " . $subject . "</th></tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
for($i = 0; $i < mysql_num_rows($doClassQry); $i++)
{
if($i % 7 == 0)
{
echo "</tr><tr><td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
else
{
echo "<td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
?>
This is my php file (saveTest.php)
<?php
$absent = $_POST['absent'];
//echo "absnt" . $absent[] . "<br>";
echo count($absent);
?>
Add name to hidden field:
$("#collect").append("<input type='hidden' name="absent[] value= '" + currentCellText + "'/>" + currentCellText);
It looks like you want to submit a javascript array to a php script and then make use of it. You can make use of .each() function to loop through all the hidden values and adding them into the array. Then use $.post to submit the array to a php script.
<script src="jquery.js"></script>
<script>
$(function(){
$('#btn_submit').click(function(){
var array_hidden = [];
$('input[type=hidden]').each(function(index){
var current_value = $.trim($(this).val());
array_hidden[index] = current_value;
});
$.post('arraysubmit.php', {'hidden_array' : array_hidden}, function(data){
$('#results').html(data);
});
});
});
</script>
<?php for($x=0; $x<=10; $x++){ ?>
<input type="hidden" name="name[]" value="Name<?php echo $x; ?>">
<?php } ?>
<input type="button" id="btn_submit">
<div id="results"></div>
You can then access the array in the php script using the post variable and do whatever you want with it:
$_POST['hidden_array']

PHP: $_POST["startId$i"]) != ""

I am trying to process a form that is dynamically created and therefore varies in length. The while loop seems to work fine. However, the 'if' statement is not; it should only print the startId$i and corId$i if and only if the form's particular text field was filled in. The code is printing a line for every text field on the form, regardless of if it was left empty or not.
$i = 0;
while(!is_null($_POST["startId$i"])){
if(($_POST["startId$i"]) != ""){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
$i = 0;
while(isset($_POST["startId$i"])){
if( !empty($_POST["startId$i"]) ){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
Can you manage with fields names ?
If yes, better way is to name inputs with name="startId[0]" and name="corId[0]" and so on...
Then in PHP you just do:
$startIds = $_POST['startId'];
$corIds = $_POST['corId'];
foreach ( $startIds as $k => $startId ) {
if ( !empty($startId) ) {
$corId = $corIds[$k];
echo "startId: " . $startId . " ---<br>";
echo "corId: " . $corId . " ---<br>";
}
}
You should use empty() in this case:
if(!empty($_POST["startId$i"])) {
...
}
I suggest to check the real content of $_POST. You can do that via var_dump($_POST);
You may find out, for example, that the empty fields contain whitespaces. In that case the trim() function may help.
For example:
while(isset($_POST["startId$i"])){
if(trim($_POST["startId$i"])){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}

Categories