How to check a number is armstrong or not using php? - php

I made a program to check whether a number is a amstrong number or not in php. But it is not working. Cloud anyone tell me what is wrong in this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="New Text Document.php" method="post">
<input type="number" placeholder="number" name="amst">
<input type="submit">
</form>
<?php
if(empty($_POST)){
exit;
}
# storing the input in a variable called amst
$amst = $_POST['amst'];
# storing the length of the input in a variable called len
$len = strlen($amst);
$add = 0;
while($amst<=0){
$div = $amst%10;
$pow = pow($div,$len);
$add+=$pow;
$amst = intval($amst/10);
}
#printing the add.
echo $add;
?>
</body>
</html>
Here I printed add just to see whether it is working properly or not. Here no matter what the input is the answer is 0. I am only getting 0. Could anyone tell me why I am getting the output as 0. I have implemented amstrong number program in other languages. This is the method I use. But here it is not working.

Your loop requires a negative number. It works only if number <0, try :
$add = 0;
while($amst>0){
$div = $amst%10;
$pow = pow($div,$len);
$add+=$pow;
$amst = intval($amst/10);
}
#printing the add.
echo $add;
if ($add=== $_POST['amst']) {
echo ‘This is an amstrong number’;
} else {
echo ‘Nope’;
}

You can check the number is Armstrong not using blow code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="post">
<input type="number" placeholder="number" name="amst">
<input type="submit">
</form>
<?php
if(empty($_POST)){
exit;
}
$num = $originalNum = $remainder = $result = 0;
# storing the input in a variable called amst
$num = (int)$_POST['amst'];
$originalNum = $num;
for($i=1;$i<=strlen($originalNum);$i++){
// remainder contains the last digit
$remainder = (int)$originalNum % 10;
//store sum of each number's cube
$result += (int)($remainder * $remainder * $remainder);
// removing last digit from the orignal number
$originalNum /= 10;
}
if ($result == $num):
echo $num." is an Armstrong number.";
else:
echo $num." is not an Armstrong number.";
endif;
?>
</body>
</html>

Related

Sending a variable from a PHP file to another PHP file

This is a simplified version of a project I'm working on.
The main idea is that test.php sends 'acct-id' to submitData.php and it validates if the account ID already exists in the server. In case it already exists, I want to send an error message to test.php.
I have built this code but I can't get '$err_msg' to change it's value in test.php. This variable changes it's value within the 'while' loop but it does not change outside it.
How can I send $err_msg value to test.php?
Thanks in advance to all possible help.
test.php
<?php
include 'submitData.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="submitData.php" method="POST">
<input type="text" name="acct-id">
<input type="submit" name="submit-btn">
<?=$err_msg?>
</form>
</body>
</html>
submitData.php
<?php
include '../tools/db_config.php';
$err_msg = "test";
if(isset($_POST["submit-btn"])){
$acct_id = $_POST["acct-id"];
$sql = "SELECT * FROM accounts WHERE acct_id='$acct_id'";
if ( $result = $conn->query($sql) ){
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$err_msg = "This account already exists.";
}
header('Location: test.php');
}
}else {
$output="Error en la consulta: ".$conn->error;
}
}
?>
You can use Session for this.
<?php
include '../tools/db_config.php';
session_start();
$err_msg = "test";
if(isset($_POST["submit-btn"])){
$acct_id = $_POST["acct-id"];
$sql = "SELECT * FROM accounts WHERE acct_id='$acct_id'";
if ( $result = $conn->query($sql) ){
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$err_msg = "This account already exists.";
}
$_SESSION['err_msg'] = $err_msg;
header('Location: test.php');
}
}else {
$output="Error en la consulta: ".$conn->error;
}
}
?
<?php
include 'submitData.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="submitData.php" method="POST">
<input type="text" name="acct-id">
<input type="submit" name="submit-btn">
<?=$_SESSION['err_msg']?>
</form>
</body>
</html>

Second Page Session Variable Not Showing Session Variable From First Page

So, I created a session_start and created two html input text boxes on the first page. I thought I correctly coded the if statements in the primary PHP block but alas, am unable to use the submitted values on the secondary page. I've made small alternations on both pages, nothing major, but cannot get the second page to show these session variables. What am I missing here?
//FIRST Page
<!DOCTYPE>
<?php
session_start();
?>
<html>
<head>
<title>Product Page</title>
<meta charset="UTF-8"
</head>
<body>
<form method=“post” action="orderPage.php">
<p>Enter the number of items you would like to order in each respective text box</p>
<label>Apples <input name="Apples" /></label>
<br>
<label>Bananas <input name=“Bananas” /></label>
<input type="submit" value="Checkout"></form>
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['Apples'])) {
$Apples = 0;
$_SESSION['Apples'] = $Apples;
} else {
$Apples = $_POST['Apples'];
$_SESSION['Apples'] = $Apples;
}
if (empty($_POST['Bananas'])) {
$Bananas = 0;
$_SESSION['Bananas'] = $Bananas;
} else {
$Bananas = $_POST['Bananas'];
$_SESSION['Bananas'] = $Bananas;
}?>
</body>
</html>
//Second Page
<!DOCTYPE>
<?php
session_start();?>
<html>
<head>
<title>Product Page</title>
<meta charset="UTF-8"
</head> <body> <h3>Order Confirmation Page</h3>
<?php
echo "Apples : " . $_SESSION['Apples'] . "<br>";echo "Bananas : " . $_SESSION['Bananas'] . "<br>";?>
<input type="submit" method="post" value="Checkout">
<?php
if (isset($_POST['submit'])){echo "Your order has been placed.";session_destroy();}?>
</body>
</html>
You Have some mistakes, there are, } missing end of the page 1 submit form, and and not using PHP function top of the page. So I have tested and following code will helps you.
page 1
session_start();
$Apples = 0;
$Bananas = 0;
if (isset($_POST)) {
if (empty($_POST['Apples'])) {
$_SESSION['Apples'] = $Apples;
} else {
$Apples = $_POST['Apples'];
$_SESSION['Apples'] = $Apples;
}
if (empty($_POST['Bananas'])) {
$_SESSION['Bananas'] = $Bananas;
} else {
$Bananas = $_POST['Bananas'];
$_SESSION['Bananas'] = $Bananas;
}
//echo json_encode($_SESSION);
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="orderPage.php" method="post">
Apples: <input type="text" name="Apples"><br>
Bananas: <input type="text" name="Bananas"><br>
<input type="submit">
</form>
</body>
</html>
And Your 2nd page
<?php
session_start();
if (isset($_POST)) {
session_destroy();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Product Page</title>
<meta charset="UTF-8">
</head> <body> <h3>Order Confirmation Page</h3>
<?php
echo "Apples : " . $_SESSION['Apples'] . "<br>";echo "Bananas : " . $_SESSION['Bananas'] . "<br>";?>
<form class="" action="" method="post">
<input type="submit" value="Checkout">
</form>
</body>
</html>
Think this will help you.

Switching output with sessions

I have a bit of code where I try to make a switch program.
Meaning that I want to have one value when clicking on a button and then another if I click it again. But I just can't figure out how.
It should echo "Yes" and then "No", front and back.
Anybody here that knows how I can solve this problem? I have been trying for hours on end, practicing my PHP.
<?php
session_start();
var_dump($_SESSION);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_SESSION['NO']) && $_SESSION['NO'] = true) {
echo "No";
$_SESSION['YES'] = true;
}
if(isset($_POST['submit'])) {
echo "Yes";
$_SESSION['NO'] = true;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
<input type="submit" name="submit" value="CHANGE">;
</form>
</body>
</html>
Use ONE session variable, like $_SESSION['STATE'] then the management of its state is simpler.
Also = is an assigment operator and == is for value comparison.
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['submit'])) {
// reverse the state
$_SESSION['STATE'] = ! $_SESSION['STATE'];
}
} else {
// page running for the first time so has not been submitted
// so initialise the session
// this will ensure you get a value output the first time the page is run
$_SESSION['STATE'] = false;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>Current State = <?php echo $_SESSION['STATE'] ? 'YES' : 'NO'; ?></p>
<form method="post">
<input type="submit" name="submit" value="CHANGE">;
</form>
</body>
</html>
Set an initial value for the session variable if it does not exist and use 1- $value ( where $value is either 1 or 0 ) to toggle the value.
<?php
session_start();
if( !isset( $_SESSION['state'] ) ) $_SESSION['state']=0;
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$_SESSION['state'] = 1 - $_SESSION['state'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<?php
if( isset( $_SESSION['state'] ) ){
echo $_SESSION['state'] ? 'Yes' : 'No';
}
?>
<form method="post">
<input type="submit" name="submit" value="CHANGE" />
</form>
</body>
</html>

How can I use data sessions in PHP?

I'm trying to use data sessions for checking a form, but, when I send user and password, and programme goes to check password, this return to main page.
I write 1234 on password field, but I can't understand why this don't work correctly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Check</title>
</head>
<body>
<?php
$usuario = trim(htmlspecialchars($_REQUEST['username'], ENT_QUOTES, "UTF-8"));
$clave = trim(htmlspecialchars($_REQUEST['password'], ENT_QUOTES, "UTF-8"));
setcookie("usuario", $usuario, time()+60*60*24*365);
session_start();
$_SESSION['nom_user'] = $usuario;
$_SESSION['pass_user'] = $clave;
header('Location: nacimiento.php');
?>
Volver
</body>
</html>
Second Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fecha de Nacimiento</title>
</head>
<body>
<?php
session_start();
if (($_SESSION['pass_user'])=='1234'){
echo '<form action="check.php" method="POST">';
echo '<label for="fecha_nac">Fecha de Nacimiento</label><input type="date" name="fnacim" id="fnacim" />';
echo '<input type="submit" name="Enviar" />';
echo '</form>';
} else {`enter code here`
header('Location: index.php');
}
?>
Volver>
</body>
session_start() must be called before any output to the browser.
Please update your code on all php pages that use the session to be included first.
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fecha de Nacimiento</title>
</head>
<body>
<?php
if (($_SESSION['pass_user'])=='1234'){
echo '<form action="check.php" method="POST">';
echo '<label for="fecha_nac">Fecha de Nacimiento</label><input type="date" name="fnacim" id="fnacim" />';
echo '<input type="submit" name="Enviar" />';
echo '</form>';
} else {`enter code here`
header('Location: index.php');
}
?>
Volver>
</body>

Higher / lower game

I'm trying to make a higher / lower number game. So basically you get one number and the start and then you click a button - higher or lower. So if you click higher and the next number is higher you win otherwise you lose , same goes for lower.The problem comes when I click some of the buttons it gives a new number. So how can I prevent this? Here's my code:
<!DOCTYPE html>
<html>
<head>
<title> Gamble </title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<?php
include('config.php');
if(!$_SESSION['username']) {
header("Location: index.php");
}
Menu();
isOnline();
$number = rand(0, 100);
echo $number;
if(isset($_POST['higher']) || isset($_POST['lower'])) {
$num = $number;
$newNumber = rand(0, 100);
if($_POST['higher']) {
if($newNumber > $num) {
echo 'You win!<br>'.$newNumber;
}
}
}
?>
<form method="POST">
<input type="Submit" name="higher" value="Higher">
<input type="Submit" name="lower" value="Lower">
</form>
</body>
</html>
*Note: I know the lower button does not work , I just want to make it for higher 'cause it will work on the same way with lower..
EDIT:
Working version:
<!DOCTYPE html>
<html>
<head>
<title> Gamble </title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<?php
include('config.php');
if(!$_SESSION['username']) {
header("Location: index.php");
}
Menu();
isOnline();
$num1 = rand(1, 100);
if(isset($_POST)) {
if($_POST['higher']) {
$num2 = rand(1, 100);
$oldNum = intval($_POST['num1']);
if($num2 > $oldNum) {
echo "You win! Your number:".$oldNum." , and the new number is: ".$num2;
}
}
}
?>
<form method="POST">
<input type="Hidden" value="<?= $num1 ?>" name="num1"><?= $num1 ?><br>
<input type="Submit" name="higher" value="Higher">
<input type="Submit" name="lower" value="Lower">
</form>
</body>
</html>

Categories