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>
Related
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>
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>
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>
i mange to populate the select by calling data on database
how will i call other data related from the value of the select using database.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
</head>
<body>
<?php
$conn = new mysqli('localhost', 'root', 'a', 'emp_table')
or die ('Cannot connect to db');
$result = $conn->query("select * from emp");
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
?>
</body>
</html>
Try this
As per #Nikhil suggested the link
https://www.w3schools.com/xml/ajax_intro.asp
You can achieve this using AJAX. Time to learn the AJAX now.
For connection
If you are working on the localhost the no need to require the password. It should be blank.
I just added the onchange function to the select tag. So whatever the user selects from the dropdown it will call the function getRole and pass the Id to the process page. Process page will return the value related to the ID and display in the span tag.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "emp_table";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
</head>
<body>
<select name="emp_name" id="emp_name" onchange="getRole(this.value);" >
<option selected disabled>Select</option>
<?php
$result = $conn->query("select * from emp");
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$name = $row['name'];
?>
<option value="<?php echo $id;?>"><?php echo $name;?></option>
<?php }}?>
</select>
<span id="emp_details"></span><!--it will display the emp record from process page-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function getRole(val){
var id=$('#emp_name').val();
$.ajax({
url:'process.php',
type:'POST',
data:'id='+id,
success:function(data)
{
//alert(data);
$("#emp_details").html(data);
},
});
}
</script>
</body>
</html>
Process.php
<?php
if (isset($_POST['id'])) {
echo $country_id=$conn->real_escape_string(trim($_POST['id']));// here you will get the id of the employee
/*your more code here*/
}
?>
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>