I've attempted to make a square root calculator with PHP and HTML using form. but it won't seem to get the output statement. Here it is:
<?php
$num = $_POST['getroot'];
$pull_sqrt = print(sqrt($num));
print("The Square root of "$num"is "$pull_sqrt);
?>
<form action="root.php" method="post">
<input type="text" id="getroot" value="Number"/>
<input type="submit" id="submitroot" value="Calculate"/>
</form>
for root.php:
<?php
$num = $_POST['getroot'];
$pull_sqrt = print(sqrt($num));
print("The Square root of "$num"is "$pull_sqrt);
?>
Please help me out on explaining this, I still don't know if PHP allowed sqrt(); as a function anymore. Any way of re-editing is fine, I would like an explained way of fixing this. Thanks!
You don't have a form element named getroot
You want to do <input type="text" id="getroot" name="getroot" value="Number"/>
You cannot rely on just an id. POST requires a "named" element.
You're also missing concatenates for print("The Square root of "$num"is "$pull_sqrt);
Sidenote: Remove print from $pull_sqrt = print(sqrt($num)); otherwise it will echo as 1.
do
print("The Square root of " . $num . "is " .$pull_sqrt);
Since you're using this in one page, you need to use isset() and using action="".
<?php
if(isset($_POST['submit'])){
$num = $_POST['getroot'];
$pull_sqrt = sqrt($num);
print("The Square root of " . $num . " is " . $pull_sqrt);
}
?>
<form action="" method="post">
<input type="text" id="getroot" name="getroot" placeholder="Enter a number"/>
<input type="submit" name="submit" id="submitroot" value="Calculate"/>
</form>
You can also check if it is in fact a number that has been entered, using is_numeric().
<?php
if(isset($_POST['submit'])){
if(is_numeric($_POST['getroot'])){
$num = (int)$_POST['getroot'];
$pull_sqrt = sqrt($num);
print("The Square root of " . $num . " is " . $pull_sqrt);
// Yes, you can do the following:
$pull_sqrt = print($num * $num); // added as per a comment you left, but deleted.
}
else{
echo "You did not enter a number.";
}
}
?>
<form action="" method="post">
<input type="text" id="getroot" name="getroot" placeholder="Enter a number"/>
<input type="submit" name="submit" id="submitroot" value="Calculate"/>
</form>
Related
there!
I want to do a database search and display the result back to the user in a pre-populated HTML form.
I located the exact part in the code that is not working but I can't understand why PHP is not picked by the server. I'm using UwAMP.
To illustrate the problem here is my short snippet of code that I need help with:
<form id="st_reg" action="" method="POST">
Student Number:
<input type="number" name="s_num" min="1000000" max="3000000" > </br>
<input type="Submit" value="Search">
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['s_num'])){
$errors[] = "You forgot to enter the Student No!";
}
else{
$st_no = trim($_POST['s_num']);
}
if(empty($errors)){
//Open database connection
require('../../connect_to_database/mysql_connect.php');
//Check if the student is already in the database
$query = "SELECT * FROM student WHERE student_no = $st_no";
//Run the query
$result = mysqli_query($db_connection,$query);
if(!$result){
echo "The student does not exist!";
echo"Please <a href='index.html'>go back</a> and choose another action!";
}
elseif($result){
echo "<h2>Student Details:</h2>";
while($row = mysqli_fetch_array($result)){
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
AND the PHP code inside VALUE ATTRIBUTE is not executing when it should in reality. Don't bother about GLOBAL php tags not being closed 'cause they are in the file (I'm not that dump).
Please note all this code is inside a .php file with HTML code. This is a just the processing part after the form is submitted. I saved my time by using single-quotes for echo and escaped the sigle-quotes along the way where DB access was required. I tried curly brackets around variables, echo with double-quotes escaping double-qoutes within it but none of these attempts were successful. This is strange because I can perfectly echo $row['student_no'] outside of this context and is running fine.
I also looked at similar questions on this website. They were close but none of them had nearly to this context. I am open to any suggestions and better than that solutions.
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
should look like this:
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="' . (isset($row['student_no']) ? $row['student_no'] : '') . '">
CONTINUATION OF STRING...
The following will do what you want.
value="<?= (isset($row["student_no"]) ? $row["student_no"] : "") ?>"
You don't need to worry about all of the escaping when you're inside the PHP chunk already.
The following PHP code is for generating a random number of four digits ($numero) and using it as a validation for a simple HTML form with three input boxes. The last input box is for entering the code (the random number). If the user doesn't write the right number in that last input box the program skips its purpose, which is adding some text to a database (agregar.txt). I think the code is fine, except for if ($_POST['password'] != $numero) {. Should I change it to a string or use another kind of variable? Each time I run the code it acts as if $numero was different from password, and I'm sure I'm writing the right number. Please some help.
<html>
<body>
<center>
<h2>Agregar entradas a diccionarioie</h2>
<?php
// RANDOM FOUR DIGITS NUMBER
$numero = rand(1000, 9999);
echo "<b>Código: </b><big>".$numero."</big><p>";
if ($_POST['password'] != $numero) {
?>
<form name="form" method="post" action="">
<input title=" LEMA " size="30" type="text" name="lema" autofocus><br>
<input title=" TRADUCCIÓN " size="30" type="text" name="trad"><br>
<input title=" CÓDIGO " size="30" type="text" name="password"><br>
Gracias por colaborar <input title=" ENVIAR " type="submit" value="•"></form>
<?php
} else {
$lema = $_POST['lema'];
$trad = $_POST['trad'];
// ADDING TEXT TO A DATABASE
$texto = $lema." __ ".$trad."\n";
$docu = fopen("agregar.txt", "a+");
fwrite($docu, $texto);
fclose($docu);
}
?>
</center>
</body>
</html>
As pointed out by #Fred -ii-, the problem in your code is the $numero get generated to different random number when you submit the form. The solution is to use session: PHP session example
The session can be used to store your $numero value after the form being submitted. Here's the updated code:
<?php
// Make sure to start the session before any output.
session_start();
if (isset($_POST['password']) && isset($_SESSION['numero']) && $_POST['password'] == $_SESSION['numero']) {
unset($_SESSION['numero']);
$lema = $_POST['lema'];
$trad = $_POST['trad'];
// ADDING TEXT TO A DATABASE
$texto = $lema." __ ".$trad."\n";
$docu = fopen("agregar.txt", "a+");
fwrite($docu, $texto);
fclose($docu);
} else {
// RANDOM FOUR DIGITS NUMBER & STORE IT IN SESSION.
$numero = $_SESSION['numero'] = rand(1000, 9999);
?>
<html>
<body>
<center>
<h2>Agregar entradas a diccionarioie</h2>
<b>Código: </b><big><?php echo $numero; ?></big><p>
<form name="form" method="post" action="">
<input title="LEMA " size="30" type="text" name="lema" autofocus><br>
<input title="TRADUCCIÓN " size="30" type="text" name="trad"><br>
<input title="CÓDIGO " size="30" type="text" name="password"><br>
Gracias por colaborar <input title=" ENVIAR " type="submit" value="•">
</form>
</center>
</body>
</html>
<?php }
Just make sure that you call session_start() before any output (in your case the HTML document).
Hope this help.
I'm learning PHP and trying to understand the if .. else statements a little better, so I'm creating a little quiz. However, I have come across an issue and I don't seem to know what the issue is. My problem is that whenever I type in the age in the input area, it will give me the $yes variable every time even if I enter the wrong age.
Here is my code so far:
My html file:
<form action="questions.php" method="post">
<p>How old is Kenny?<input></input>
<input type="submit" name="age" value="Submit"/>
</p></form>
My php file:
<?php
$age = 25;
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25){
echo "$yes";
}else{
echo "$no";
}
?>
You catch the user input inside the $_POST superglobal var (because the method of your form is POST.
So
<?php
$age = 25;
should be
<?php
$age = $_POST['age'];
There is an error in HTML too. This
<input type="submit" name="age" value="Submit"/>
should be
<input type="text" name="age" value=""/>
<input type="submit" value="Click to submit"/>
Because you want one input and one button. So one html element for each element.
and <input></input> must be cleared because it's not valid syntax :-)
<form action="questions.php" method="post">
<p>How old is Kenny?</p><input type="text" name="age"></input>
<input type="submit" value="Submit"/>
</form>
$age = (int) $_POST["age"];
$yes = "Awesome! Congrats!";
$no = "haha try again";
if ($age == 25) {
echo $yes;
} else {
echo $no;
}
<?php
/* Test that the request is made via POST and that the age has been submitted too */
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['age'] ) ){
/*
ensure the age is an integer rather than a string ..
though for this not overly important
*/
$age=intval( $_POST['age'] );
if( $age==25 ) echo "Congratulations";
else echo "Bad luck!";
}
?>
<form action="questions.php" method="post">
<p>How old is Kenny?
<input type='text' name='age' placeholder='eg: 16' />
<input type="submit" value="Submit" />
</p>
</form>
A simple html form, note that the submit button does not carry the values you want to process, they are supplied via the input text element.
First of all, you need to echo the variable; echoing "$no" will keep it as a string. Remove the quotes from "$no" and "$yes" in your if then statement. Otherwise, your code seems sound!
Newbie here working with a simple form that asks user to enter two ints and then adds them together and prints out the total. I've gone over it multiple times and it seems that my nuns aren't catching the numbers or maybe the ints are initializing properly? I'm not sure - i'm a newb and confused. Any help is appreciated (and yes i've searched for an answer via google and php.net but i'm not at a level that i understand what i'm reading well enough to sort it out i guess).
Code:
<?
//adder.php
if (isset($_POST['num1']))
{
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$myTotal = $num1 + $Num2;
echo "<h2 align=center>You added <font color=blue>" . $num1 . "</font> and ";
echo "<font color=blue>" . $num2 . "</font> and the answer is <font color=red>" . $myTotal . "</font>!";
unset($_POST['num1']);
unset($_POST['num2']);
}else{
?>
<html>
<body>
<h1 align="center">Adder </h1>
<form action="<? print $_SERVER['PHP_SELF']; ?>">
Enter the first number:<input type="text" name="Num1"><br>
Enter the second number:<input type="text" name="num2"><br>
<input type="submit" value="Add Em!!">
</form>
</body>
</html>
<?php
echo "<br />Reset page";}
?>
You are using POST, you need to use GET
if (isset($_GET['num1']))
{
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
...
PHP array keys are case sensitive, and HTML form elements are submitted with the identical case they have in the HTML:
if (isset($_POST['num1']))
^---small n
Enter the first number:<input type="text" name="Num1"><br>
^---big N
since you're checking for the wrong form element, your addition code will never run.
Case sensitivity. Right here:
<input type="text" name="Num1">
But in your PHP script your looking for "num1". Remember, keys in associative arrays are case sensitive.
$thing['foo'];//and
$thing['Foo'];//are two separate values.
Also, your form is set to the default method, which is GET. Try adding
action="POST"
as an attribute to it.
As a side suggestion, you don't need to string concat your variables if you're using double quotes to delimit your strings. A double quote tells the parser that a variable could be in the string and to parse it as such.
You can also just change form to post method by default a form will use get.
Here you can see pros/cons http://www.w3schools.com/tags/att_form_method.asp
i corrected the other case sensitive mistakes mentioned.
I'm learning php too but i put it together in case it helps
<?
//adder.php
if (isset($_POST['num1']))
{
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$myTotal = $num1 + $num2;
echo "<h2 align=center>You added <font color=blue>" . $num1 . "</font> and ";
echo "<font color=blue>" . $num2 . "</font> and the answer is <font color=red>" . $myTotal . "</font>!";
unset($_POST['num1']);
unset($_POST['num2']);
}else{
?>
<html>
<body>
<h1 align="center">Adder </h1>
<form action="<? print $_SERVER['PHP_SELF']; ?>" method="post">
Enter the first number:<input type="text" name="num1"><br>
Enter the second number:<input type="text" name="num2"><br>
<input type="submit" value="Add Em!!">
</form>
</body>
</html>
<?php
echo "<br />Reset page";}
?>
Using the following code I am attempting to:
Test to see if one of the dynamically assigned field names has been submitted;
Use the "Actionable Code" to process the submitted information.
My problem lies in I am incapable of retrieving the appropriate dynamic variable name. $this->get_field_name('email_to') will output a name variable such as widget-mywidget[3][email_to]; but to access this value via PHP I need it in the form of $_POST['widget-mywidget'][3]['email_to'].
How can I go about solving this dilemma?
OUTPUTTED HTML:
<form id="widget-mywidget-3-osiris_contact" method="post" action="">
<fieldset>
<input type="text" name="widget-mywidget[3][user_name]">
<input type="text" name="widget-mywidget[3][user_email]">
<textarea name="widget-mywidget[3][user_message]"></textarea>
</fieldset>
<fieldset>
<input type="hidden" name="widget-mywidget[3][email_to]" value="">
<input type="hidden" name="widget-mywidget[3][email_subject]" value="">
<button type="submit" name="widget-mywidget[3][email_send]">Send</button>
</fieldset>
</form>
PROCESSING PHP:
if(in_array($this->get_field_name('email_to'), $_POST)){ // <--- Where I need help.
// Actionable Code
}
This is what $this->get_field_name does:
function get_field_name($field_name) {
return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
}
I suggest that you print_r($_POST) and compare it visually for better debugging...
(Or use a debugger...)
$thing = "widget-mywidget[3][email_to]";
$exp = explode("[", $thing);
$get_it = $_POST['".$exp[0]."[".$exp[1]."[".$exp[2]."'];
Try, if it works.