Php script find square root of a given number error - php

I simple php program that returns the square root of a number, although when I echo the results, I get the following error and I am tired, so Im probably missing something really small here.
Code:-
<!DOCTYPE html>
<html>
<head><title>Task 2</title></head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
class square
{
public $num=null;
public $objRes=null;
function processRequest()
{
$this->square=$_REQUEST['num'];
}
function run()
{
if(isset($_REQUEST['submit']))
{
$this->processRequest();
$this->objRes=sqrt($this->square);
}
}
}
$objSquare=new square();
$objSquare->run();
?>
<form action="task2.php" method="POST">
Enter the number:<input type="text" name="num"/>
<input type="submit" value="Submit">
</form>
<?php
if($objSquare->res!=0) {
echo "Square root of a given number is ".$objSquare->objRes." ";
}
?>
</body>
</html>
Heres my error:-
Notice: Undefined property: square::$res in /Applications/MAMP/htdocs/test/task-2/task2.php on line 46

Change $objSquare->res to $objSquare->objRes because that's the name of your square class property.

I know it's not what you asked for. But sometimes people don't know they wanted something until they have it.
Example using sqrt()
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...

Related

php/mysql: credit card validation isn't working

I tried to make this program that takes a credit card number and checks if it it valid or not and let the user know about it but in my program, i dont get echo message at all on clicking submit
<?php
session_start();
if (isset($_POST['submit'])){
$number=$_POST['cc'];
$total=0;
$i=1;
$last4= substr($number,-4,4);
$number=$str_split($number);
$number=array_reverse($number);
foreach($number as $digit){
if(i%2==0){
$digit*=2;
if($digit>9){
$digit -=9;
}
}
$total += $digit;
$i++;
}
if($total%10==0){
echo "Your credit card number ending in ".$last4." is valid";
}
else
{
echo "Your credit card number ending in ".$last4." is invalid";
}
}
?>
<html>
<head>
<title>Credit Card Number</title>
</head>
<body>
<form action="cards.php">
<input type="text" name="cc">
<input type="submit" name="submit">
</form>
</body>
</html>
Let's go over this, one step at a time.
Firstly, the following condition never gets met/satisfied, since you're using a POST array against a form that does not (specifically) contain a "post" method in it <form action="cards.php">.
if (isset($_POST['submit'])){
// ...
}
Since forms default to a "GET" method when "POST" was not implied, it needs to be included.
<form action="cards.php" method="post">
Next, we have the following error (pulled from and stated in comments):
"Notice: Undefined variable: str_split"
str_split() should have been declared as a function, rather than a variable.
$number=$str_split($number);
^ $ is a variable character
It needs to be removed:
$number= str_split($number);
And then we have the following error (also pulled from and stated in comments):
Use of undefined constant i - assumed 'i'"
That was caused by the missing $ for the "i" in if(i%2==0) and is first declared in $i=1;.
It looked for a constant of that name, and since it did not find one, it threw you that error.
Therefore, it should read as:
if($i%2==0)

Get input from HTML form in PHP

I'm learning MySQL and PHP and got a problem with the input of the form. So I wrote a small test code, but it still cannot work. My PHP version is 5.6.
The code:
<html>
<body>
<form action ="2.php" method ="post">
Name: <input type="text" name="username" />
<input type ="submit" value="ok" />
</form>
</body>
</html>
and
<html>
<?php
if(isset($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>
The output of the project is always error, can't output the input before.
I tried single quote and double quote for username, both can't work.
I also tried to set always_populate_raw_post_data in php.ini to 0, -1, 1, all can't work.
I don't know where the problem is, though it might be very silly.
As what it look it is correct and should run without any problem. Make sure the above code is what you actually have. From my experience most of the form submission can be
you don't have correct name (username)
you might send incorrect http verb (post)
you submit to wrong endpoint (2.php)
From you code above everything look fine. if you still don't have the right result, you better debug it with var_dump, or print_r function with these built-in
$_POST, $_GET, $_REQUEST and check whether they contains you form variable name username
You are using isset as a variable, but it is a function that returns a boolean.
Change $user=isset($_POST['username']); to $user=$_POST['username'];
Another thing is that in both case you will end up in the IF condition even if there is no value added to the field so you can do something like this too:
<html>
<?php
if(isset($_POST['username']) && !empty($_POST['username'])){
$user=$_POST['username'];
echo $user;
echo " is your name";
}
else{
$user=null;
echo "error";
}
?>
</html>

Using generated php variable as name for html <input> object in loop

On the first page (index.php) I wrote this:
<?php
echo '<form action="test.php" method="get">';
$x=0;
while($x<5){
$x++;
$test='tester'.$x;
echo '<input type="text" name="$test"><br>';
};
echo '<input type="submit" value="submit">';
?>
on the second page (test.php) I wrote this:
<?php
echo $_POST['tester1'];
echo $_POST['tester2'];
echo $_POST['tester3'];
echo $_POST['tester4'];
echo $_POST['tester5'];
?>
and when I tested it I got these errors
Notice: Undefined index: tester1 in C:\xampp\htdocs\test.php on line 2
Notice: Undefined index: tester2 in C:\xampp\htdocs\test.php on line 3
Notice: Undefined index: tester3 in C:\xampp\htdocs\test.php on line 4
Notice: Undefined index: tester4 in C:\xampp\htdocs\test.php on line 5
Notice: Undefined index: tester5 in C:\xampp\htdocs\test.php on line 6
The code below is an example for the real code being meant for users to fill in a number. I want to use these numbers later for calculations so they all need an unique name. The <input> objects are generated via a loop, the amount of times the loop runs is specified by the amount of rows in a database.
The two main issues are that you are using PHP variables inside single quotes, this doesn't pass the actual variable, but the actual name. As an example
$foo = "bar";
echo 'This is $foo';
would print
This is $foo
If you use double-quotes, the variable's content would be passed,
$foo = "bar";
echo "This is $foo"; // You can also do the following: echo 'This is '.$foo;
would print
This is bar
Secondly, you are using method="get" in your form, but trying to retrieve them as POST variables. This means that you have to change it to method="POST".
Another alternative, is to create an array of elements, and use a loop in PHP to retrieve the values. An example given below. The first snippet generates a form with 5 input-fields as an array.
<form action="test.php" method="POST">
<?php for ($x=0; $x<5; $x++) { ?>
<input type="text" name="tester[]" />
<?php } ?>
<input type="submit" name="submit" />
</form>
And in PHP, loop through that array.
<?php
if (isset($_POST['tester']) {
// If the values are set, to avoid Undefined Index notices
foreach ($_POST['tester'] as $value) {
echo $value."<br />";
}
}
?>
This is how it works (index.php):
<?php
echo '<form action="test.php" method="post">';
$x=0;
while($x<5){
$x++;
$test='tester'.$x;
echo '<input type="text" name="'.$test.'"><br>';
};
echo '<input type="submit" value="submit">';
?>
simply append this code to the top of test.php
if(!isset($_POST['tester1']) || !isset($_POST['tester2']) ... etc){
exit(0); //or do something to signal index.php of missing values
}
/* (the rest of the code */
When writing a dynamic page like this, you should always expect there to be a missing variable and code an escape so you never run into an error such as that.

PHP error when creating an array

I apologize in advance because I am very new to programming and am in a rush to get this complete as I am running on a deadline, this is also my first time using this webpage or in fact any forum.
I am required to create a simple array and loop in PHP that stores and prints the name of 3 tennis players.
My code is as follows:
html>
<head>
<title>Tennis Players Array</title>
</head>
<body>
<form action="" method="POST">
<input type="text" name="name">
<input type="submit" value = "submit">
</form>
<p>
<?php
$request = $_SERVER['REQUEST_METHOD'];
$name = $_POST['name'];
if ($request == 'GET')
{
// Do Nothing
}
else if ($request == 'POST')
{
$TennisPlayers = array("Roger Federer", "Rafael Nadal", "Novak Djokovic");
echo $TennisPlayers;
}
?>
</p>
</body>
</html>
I am getting an error when I run the code:
"Notice: Array to string conversion in C:\xampp\htdocs\Problem3\ProblemThree.php on line 19"
Line 19 is
echo $TennisPlayers;
And this is likely not going to be the only error once this one is corrected.
Look, I understand you aren't going to give me the direct answer to this and I appreciate that although I would really like some assistance in getting this to work.
P.S Sorry for such a rookie question.
Thank You! :)
Its because you can't echo an array in order to print your array you need to use print_r or var_dump. But in your case you need to show the values so you can use it as
echo implode(',',$TennisPlayers);
You cannot print an array, you have to loop the array to get each elements:
foreach ( $TennisPlayers as $single_player ) {
echo $single_player . '<br>';
}
This code will print:
Roger Federer
Rafael Nadal
Novak Djokovic
You have to use print_r or var_dump if you want to show the array. You can't use echo.
// doesn't work
echo $TennisPlayers;
// works
var_dump($TennisPlayers);
// works
echo '<pre>';
print_r($TennisPlayers);
echo '</pre>';

Can't use function return value

I'm new to PHP and developing a login form. Please find below the code I used. When I tried it gave me the following error:
Fatal error: Can't use function return value in write context in
C:\xampp\htdocs\forsiteSystem\login.php on line 3
Please help me to fix the issue.
Source code for thems/login.html:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action=".\login.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" id="Submit_button">
</form>
</body>
</html>
Source code for index.php:
<?php
// venushka thisara dharmasiri
require 'config.php';
require 'thems\login.html';
?>
Source code for login.php:
<?php
if(isset($_POST("Submit_button"))==true)
print("Submit button pressed");
else
print("submit button sorry");
?>
Source code for config.php:
<?php
$dbUser="root";
$dbPassword="";
$dbName="forsitelogin";
$dbHost="localHost";
$dbConnection= mysql_connect($dbHost, $dbUser, $dbPassword);
if($dbConnection)
{
mysql_select_db($dbName);
//print("Sucessfully connected to database");
}
else
die("<strong>Cound not connect to database </strong> ");
?>
Should be $_POST["Submit_button"] instead of $_POST("Submit_button")
The error the script returns explains it:
Fatal error: Can't use function return value in write context in
C:\xampp\htdocs\forsiteSystem\login.php on line 3
If you don’t understand the meaning of the error—and believe me, most error messages are bizarre even to experienced programmers—look at the line number referenced. And looking at line 3 in login.php shows me the error; $_POST("Submit_button") is invalid:
if(isset($_POST("Submit_button"))==true)
print("Submit button pressed");
else
print("submit button sorry");
It should be $_POST["Submit_button"]:
if(isset($_POST["Submit_button"])==true)
print("Submit button pressed");
else
print("submit button sorry");
But looking at it further, why is there an ==true? It can simply be like this:
if(isset($_POST["Submit_button"]))
print("Submit button pressed");
else
print("submit button sorry");
But I would recommend doing a better check on that value like this:
if(array_key_exists("Submit_button", $_POST) && !empty(trim($_POST["Submit_button"])))
print("Submit button pressed");
else
print("submit button sorry");
I find that using array_key_exists and a combination of !empty with trim works better for basic user submitted data verification.
First some code clean up might help. PHP does not require braces in if() else syntax; however, a great place to start. I would suggest diving into basic syntax of PHP here. Not that what is there would not work.
if(condition){
//do something
} else {
//do something else
}
The main issue you are experiencing is proper syntax for arrays in PHP. Thus this will solve your fatal error.
//old
$_POST("Submit_button")
//new
$_POST['foo']
This fixes your first fatal error; conversely, will not get you much further. Since your form is using 'GET' not 'POST' to send the variables to the script. The submit button does not return a variable; rather, use another <input> or add a name to the form <form name="form" action="file.php" method="post"> to retrieve a variable. Hence using:
if(isset($_POST['form'])){
echo $_POST['name'];
}
Furthermore, there are many concerns using $_GET variables and mysql_connect. I would suggest using Google to find some good tutorials on PHP mysqli or PDO before moving on.

Categories