Sending a variable from a PHP file to another PHP file - php

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>

Related

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>

Call related data with populated select from php database

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*/
}
?>

Cannot get session value with php

i'm sending session values from my first.php and trying to get from my second.php. I have done some reading about this, and works fine on my localhost, but on my server doesn't work at all.
Here is the code from my first.php file:
<?php
session_start();
ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="http://localhost/Shopping_biblioteka/css/style.css">
<title></title>
</head>
<body align="center">
<div id="login">
<?php
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
mysql_connect("localhost", "shopping_katalog", "logik#112233") or die(mysql_error());
mysql_select_db("shopping_katalog") or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES utf8");
$result = mysql_query("SELECT password,id FROM x9qg6_users
where username='" . $username . "'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
$userhash = md5($password . $test[1]);
if ($test[0] === $userhash) {
$_SESSION['login_user'] = $user_id;
$_SESSION['username'] = $username;
$url = "biblioteka.php";
header("Location: $url");
}
} else {
echo 'Внесете ги вашите податоци во полињата!';
}
?>
<form action="" method="POST" accept-charset="UTF-8">
Корисничко име:<br/>
<input name="username" id="username" type="text"/><br/>
Лозинка:<br/>
<input type="password" id="password" name="password"/><br/>
<input type="submit" value="Логирај се!"/>
</form>
</div>
</body>
</html>
And here is my second.php file:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="http://localhost/Shopping_biblioteka/css/style.css">
<title>Библиотека на</title>
</head>
<body>
<div id="wrapper">
<?php
$user_ID = $_SESSION['login_user'];
$logged_user = $_SESSION['username'];
?>
<h1 align="center" id="b_welcome">Добредојде <?php echo $logged_user; ?> во твојата библиотека! </h1>
<h4 align="center" id="b_info">Во твојата библиотека ги имаш следниве книги</h4>
<div id="knigi">
<?php
/* OVA E QUERITO
*
SELECT *
FROM Knigi k, poracki p
WHERE k.knigaid = p.kniga
AND p.korisnikInt = $user_ID
*
*/
//-----------------------------------
if(isset($_SESSION['login_user'])){
mysql_connect("localhost", "user", "pass) or die(mysql_error());
mysql_select_db("shopping_katalog") or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES utf8");
$result = mysql_query("SELECT * FROM Knigi k, poracki p
WHERE k.knigaid = p.kniga AND p.korisnikInt ='" . $user_ID . "'");
while ($row = mysql_fetch_array($result)) {
//knigaid,naslov,avtor,link_do_pdf,thumb_link,kategorija,cena,br_strani
echo '<div id="item">';
echo '<h5 align="center" id="b_item_title">' . $row['naslov'] . '</h5>';
//echo '' . $row['avtor'] . '';
echo '<img src="http://' . $row['thumb_link'] . '" id="b_item_slika" />';
echo '</div>';
}
if (!$result) {
echo 'Проблем со добивање на податоците: ' . mysql_error();
exit;
}
}else{
$url = "/index.php";
header("Location: $url");
}
?>
</div><!--kraj na knigite-->
</div>
</body>
</html>
Here is the concept:
in you first_page.php the user should enter his username and password and if you find them both are correct and match those exist in the database, then you will set a session and store whatever data you want in it, then you will redirect the user to the second_page.php which will use those session stored values to do whatever you want with them. And if the user didn't enter his username and password he will stay in the first_page.php
And here is a simple example from which you can take the main concept and apply it on your case:
in first_page.php
<?php
session_start();
ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body align="center">
<div>
<?php
if (!empty($_POST["username"]) && !empty($_POST["password"])) {
$_SESSION['username'] = $_POST["username"];
header("Location: second_page.php");
}
?>
<form action="first_page.php" method="post" accept-charset="UTF-8">
Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password"/><br/>
<input type="submit" value="Login"/>
</form>
</div>
</body>
</html>
And in second_page.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h3>Welcome <?php echo $_SESSION["username"] ?></h3>
</body>
</html>
To check if cookies are enabled or not, use the code...
<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
header('Location:/info.php?cookies=true');
}
if(count($_COOKIE) > 0){
echo "Cookies are Enabled!";
} else {
echo "Disabled";
}
?>

registration php file.

I have been trying to get this sign up php to work. I'm close, I guess. But there's a problem. The result is always a button that redirects to the homepage(You'll know what I'm talkin about when you read the code.) If you could find the problem please tell me.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" id="jmtoday" class=" no_js">
<head>
<link href='icon.jpg' rel='icon' type='image/jpg'/>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-language" content="en" />
<LINK REL=StyleSheet HREF="Mainstyles.css" TYPE="text/css"></link>
<Title>Sign up to JM Today</title>
</head>
<body>
<?php
$dbservertype='mysql';
$servername='localhost';
$dbusername='***';
$dbpassword='***';
$dbname='jmtdy';
function connecttodb($servername,$dbname,$dbuser,$dbpassword)
{
global $link;
$link=mysql_connect("$servername","$dbuser","$dbpassword");
if(!$link){
die("Could not connect to MySQL");
}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
}
connecttodb($servername,$dbname,$dbusername,$dbpassword);
?>
<?php
$username=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$password2=mysql_real_escape_string($_POST['password_confirmation']);
$todo=mysql_real_escape_string($_POST['todo']);
$email=mysql_real_escape_string($_POST['email']);
$fname=mysql_real_escape_string($_POST['fname']);
$lname=mysql_real_escape_string($_POST['lname']);
if(isset($todo) and $todo=="post"){
$status = "OK";
$msg="";
}
if(!isset($username) OR strlen($username) <3){
$msg=$msg."Username should be equal to or more than 3 characters long<BR/>";
$status= "NOTOK";
}
if(mysql_num_rows(mysql_query("SELECT username FROM users WHERE username = '$username'")or die (mysql_error ()))){
$msg=$msg."Username already exists. Please try another one<BR/>";
$status= "NOTOK";}
if ( strlen($password) < 3 ){
$msg=$msg."Password must be more than 3 charactors long<BR/>";
$status= "NOTOK";
}
if ( $password <> $password2 ){
$msg=$msg."Passwords are not identical.<BR/>";
$status= "NOTOK";
}
if($status="NOTOK"){
echo "$msg<br/><input type='button' value='Retry' onClick='history.go(-1)'>";
}
else {
if(mysql_query("insert into users(username,password,email,fname,lname) values('$username','$password','$email','$fname','$lname')")or die (mysql_error ())){
echo "Welcome, You have successfully signed up";
}
else {
echo "Database Problem, please contact Site admin";
}
}
?>
</body>
</html>
You're missing an = on the line
if($status="NOTOK"){
It will assign the "NOTOK" to the $status and be boolean true.

Categories