How to save a PHP variable when a page loads twice - php

A user enters two dates periods on a text-box and a SQL select statement picks mobile numbers from a database entered in between the period. I want to pick and display them on a page. On the same display page, I have a text area where a user can type a message and on submit, it should be sent to these selected numbers and displayed mobile numbers. I am having a challenge on passing the $mobilenumber to the function sendbulk that is to send the message to the mobile numbers displayed by $mobilenumber variable. Everything else is okay apart from passing the $mobilenumber. I think this is because after the page loads to display the contacts selected, on the second load as you submit the $message to bulk function the value of $mobilenumber is already lost. How can I save it.
Check sample code below and please advice. How do I save the $mobilenumber so that by the second load it is still there to be passed to the function sendbulk()? Anyone?
<?php
//Define variable and set to empty values
$message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$message = test_input($_POST['message']);
echo "$message";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$time1 = isset($_POST['t1']) ? $_POST['t1'] : 'default something missing';
$time2 = isset($_POST['t2']) ? $_POST['t2'] : 'default something missing';
//connection
$sql = "SELECT DISTINCT msisdn FROM customer WHERE DATE_FORMAT(time_paid, '%Y-%c-%e') BETWEEN ADDDATE('$time1',INTERVAL 0 HOUR) AND ADDDATE('$time2',INTERVAL '23:59' HOUR_MINUTE)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo " Recipients: "; echo "$result->num_rows <br> <br>";
// output data of each row
while($row = $result->fetch_assoc()) {
$mobilenumber = $row['msisdn'];
echo "Mobile : " . "$mobilenumber" . "<br>";
}
} else {
echo "No Contacts to Display";
}
$conn->close();
sendbulk($mobilenumber,$message);
?>
<center></center> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<textarea name='message' rows="6" cols="60" placeholder="Please Type Your Message Here"></textarea>
<br><br>
<input type="submit" name="submit" value="Send Message">
</form></center>
<?php
function sendbulk($mobilenumber,$message) {
echo "$mobilenumber";
echo "$message";
$serviceArguments = array(
"mobilenumber" => $mobilenumber,
"message" => $message_sent
);
$client = new SoapClient("http://*******");
$result = $client->process($serviceArguments);
return $result;
}

You use sessions.
Here is a sample code:
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count'] += 1;
}
echo $_SESSION['count'];
?>
Keep reloading this file via your web server. You should see the variable incrementing.
As an alternative, you can also use $_COOKIE. The only difference is that $_SESSION is saved on the server side and not accessible on the client. To identify the client it does store a cookie for that session on the client.
$_COOKIE on the other hand is completely stored on the client and passed by the browsers to the server on every request.
Also note a caveat, don't overload your session variables or cookies as it will hit your response times.
Also note that session_start() is required in every PHP file where you want to access the session.

Related

Having problems retrieving from mysql to populate form

I'm having a problem getting a result from my mysql database and getting it to popular a form. Basically, i'm making an item database where players can submit item details from a game and view the database to get information for each item. I have everything working as far as adding the items to the database and viewing the database. Now i'm trying to code an edit item page. I've basically reused my form from the additem page so it is showing the same form. At the top of my edititem page, I have the php code to pull the item number from the url as the item numbers are unique. So i'm using a prepared statement to pull the item number, then trying to retrieve the rest of the information from the database, then setting each information to a variable. Something is going on with my code but I can't find any errors. I entered a few header calls to debug by putting information in the url bar...But the headers aren't even being called in certain spots and im not getting any errors.
In the form, I used things like
<input name="itemname" type="text" value="<?php $edit_itemname?>">
and nothing is showing in the textbox. I'm fairly new to php and it seems much more difficult to debug than the other languages i've worked with..Any help or suggestions as far as debugging would be greatly appreciated. I posted my php code below as well if you guys see anything wrong...I shouldn't be having issues this simple! I'm pulling my hair out lol.
Thanks guys!
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
}else{
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
}else{
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
}else{
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
header("Location: edititem.php?testing");
}
}
}
}
?>
To get the value of $edit_itemname into the output you should be using <?= not <?php. Saying <?php will run the code, so basically that is just a line with the variable in it. You are not telling it to print the value in the variable.
If your whole line looks like:
<input name="itemname" type="text" value="<?= $edit_itemname?>">
That should give you what you are looking for. The <?= is the equivalent of saying echo $edit_itemname;
If you don't like using <?= you could alternatively say
<input name="itemname" type="text" value="<?php echo $edit_itemname; ?>">
Your code should be change to a more readable form and you should add an output - I wouldn't recomment to use <?= - and you need to choose what you're going to do with your rows - maybe <input>, <table> - or something else?
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
} // no else needed -> exit()
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
} // no else needed -> exit()
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
} // no else needed -> exit()
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
// does not make sense here: header("Location: edititem.php?testing");
// show your data (need to edited):
echo "Name: " + $edit_itemname + "<br/>";
echo "Area: " + $edit_itemarea + "<br/>";
echo "Comment: " + $edit_itemcomments + "<br/>";
// end of current row
echo "<hr><br/>"
}
?>

how to store value till it not submit

I have 3 pages:
Register.php
Success.php
Login.php
Now when my user register the it's values validate on success.php and if not correct it returned on register page and if it get correct then it gone to login page. I want when it comes back to register page when values not correct then values which was filled before submit should remain as it.
You can do this by just returning the values the user sent in. Using $_GET
http://php.net/manual/en/reserved.variables.get.php
https://www.w3schools.com/php/php_forms.asp
Just take the paramaters the users sent in and pass them back in the url.
Like if failed, return to url:
register.php?uname=value1&email=value2
Then in register.php get the paramaters with
$username = $_GET['uname'];
Then echo it out in the form again as value:
<input id="uname" value="<?php if(isset($_GET['uname']){
echo $username;
}
else{echo "enter username";} ?>" />
Very simple example here, but just follow w3school and you should have everything you need to get this done.
As you are using PHP, so best option is to use SESSIONS.
You can create something like:
$name = $_SESSION['name'];
$email = $_SESSION['email'];
Than these values can be used in the 3 pages for processing.
Your first page is register.php, so in the beginning of page just add a php function session_destroy(); so that when user open page any live session will be destroyed and new session will be started with that specific user. Also don't forget to start sessions by using function session_start(); on every page. I hope this will solve your requirement.
Take a look at JavaScript's localStorage. (or sessionStorage)
With that you will be able to store information between pages. Then just pass all the information at the same time as POST data on the last page.
Example:
var existing = localStorage.getItem('user_name');
if (existing == null) {
// The user has not set their name, lets assume it's John Doe
existing = 'John Doe';
localStorage.setItem('user_name', existing);
}
alert('Hello ' + existing + '!');
Alternatively, on the pure PHP side of things, you could also use PHP sessions. This way all the information stays on the server instead of in the user's browser.
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
The easiest method, IMO, using PHP would be to use a session variable which holds the values of all POSTed data from register.php
A simple function can be called to retrieve the value from the session variable and consequently displayed in the HTML form fields. This is an example of how you could achieve the desired result.
<?php
/* success.php */
session_start();
function getvalue( $var='register', $field=false ){
if( isset( $_SESSION[ $var ] ) ){
return array_key_exists( $field, $_SESSION[ $var ] ) ? $_SESSION[ $var ][ $field ] : '';
}
return '';
}
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/*
a boolean to indicate if everything is OK with the submitted
data - to be updated later according to your rules
*/
$ok=false;
/* set the session variable */
$_SESSION['register']=$_POST;
/* process POST data - set value of $ok to true if everything is OK! */
/*
this is where you determine the rules for success or failure
*/
/* Determine where the use goes next */
if( $ok ){
exit( header('Location: login.php') );
} else {
exit( header('Location: register.php') );
}
}
?>
<?php
/* register.php */
session_start();
?>
<html>
<head>
<title>register.php</title>
</head>
<body>
<!--
the form fields should initially be blank, but if the user is redirected
back to the page the fields should show the values stored in the
session variable.
-->
<form name='register' method='post' action='success.php'>
<!-- various form fields - example -->
<input type='text' name='email' value='<?php echo getvalue('register','email'); ?>' />
<input type='text' name='username' value='<?php echo getvalue('register','username'); ?>' />
<!-- more fields -->
<input type='submit' />
</form>
</body>
</html>
<?php
session_start();
$_SESSION['namefeild_name'] = $_POST['namefeild_name'];
$_SESSION['mob'] = $_POST['mob'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['city'] = $_POST['city'];
if(isset($_POST['reg']))
{
$con=mysql_connect("localhost","root","");
if(!$con) { die('Could Not Connect: '.mysql_error()); }
mysql_select_db("database", $con);
if(!isset($_POST['namefeild_name']) ||
!isset($_POST['mob']) ||
!isset($_POST['pass']) ||
!isset($_POST['pas']) ||
!isset($_POST['email']) ||
!isset($_POST['city']))
{
die("<script type='text/javascript'>alert('We are sorry, but there appears to be a problem with the form you submitted.')</script>");
}
$uid = $_POST['namefeild_name']; // required
$name = $_POST['namefeild_name']; // required
$uname=$_POST['mob']; //required
$pass=$_POST['pass']; //required
$pas=$_POST['pas']; //required
$email = $_POST['email']; // required
$city = $_POST['city']; // not required
$type = 'BAL'; // not required
$id=md5($uname);
$error_message = "";
$string_exp = "/\b([A-Za-z]{1,30}[- ]{0,1}|[A-Za-z]{1,30}[- \']{1}
[A-Za-z]{1,30}[- ]{0,1}|[A-Za-z]{1,2}[ -\']{1}[A-Za-z]{1,30}){2,5}/";
if(!preg_match($string_exp,$name)) {
$error_message .= "<script type='text/javascript'>alert('Name does not appear to be valid.')</script>";
header('location:register.php?errorname');
}
$string_exp = "/^[7-9][0-9]{9}$/";
if(!preg_match($string_exp,$uname)) {
$error_message .= "<script type='text/javascript'>alert('Mobile Number does not appear to be valid.')</script>";
header('location:register.php?errormob');
}
$string_exp = "/\b([A-Za-z]{1,30}[- ]{0,1}){1}/";
if(!preg_match($string_exp,$pas)) {
$error_message .= "<script type='text/javascript'>alert('The password you entered does not appear to be valid.<br />Contain Atleast one Uppercase Letter<br />Contain atleast one lower case letter<br />contain atleast one number')</script>";
header('location:register.php?errorpass');
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$city)) {
$error_message .= "<script type='text/javascript'>alert('City does not appear to be valid.')</script>";
header('location:register.php?errorcity');
}
if(strlen($city) < 2) {
$error_message .= "<script type='text/javascript'>alert('City does not appear to be valid.')</script>";
header('location:register.php?errorcity');
}
if(strlen($error_message) > 0) {
die($error_message);
}
else
{
$query=mysql_query("select * from customer where uname='".$uname."'") or die(mysql_error());
$res=mysql_fetch_row($query);
if($res)
{
header("location: register.php?useralreadyexits");
session_destroy();
}
elseif(!$res)
{
$datetime=Date("Y/m/d H:i:s");
$result=mysql_query("INSERT INTO customer VALUES('$id','$uname','$name','$pas','$email','$city','$datetime');");
$result2=mysql_query("INSERT INTO payment VALUES('$id','$uname','25','$datetime','$type');");
if($result && $result2)
{
header("location: login.php?success");
session_destroy();
}
else
{
$_SESSION['name']=$uname;
header('location:register.php?notregistered');
}
}
}
mysql_close($con);
}
?>

Passing on validated variables to a different page (PHP)

On form index.php I have three input fields (Name, Surname and Date of Birth) which I want to pass along to form myProfile.php, the user cannot continue to the next myProfile.php unless all three fields have been completed.
How can I send the variables to the next page, once it has been determined that all the input fields are valid? Currently I can determine that all the input fields are valid, but I don't know how to pass the variables along to myProfile.php
Variables and Input handling (index.php):
<?php
$nameErr = $surnameErr = $dobErr = "";
$name = $surname = $dob = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname = test_input($_POST["surname"]);
}
if (empty($_POST["dob"])) {
$dobErr = "Date of Birth is required";
} else {
$dob = test_input($_POST["dob"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Creating the form (index.php):
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Surname:
<input type="text" name="surname">
<span class="error">* <?php echo $surnameErr;?></span>
<br><br>
Date of Birth:
<input type="date" name="dob">
<span class="error">*<?php echo $dobErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
My problem is that in order to send my name, surname and date of birth to myProfile.php, I need the form action to be action="myProfile.php", however for the input validation to take place it has to be action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>". How can I allow the input validation to take place, and if all the input is valid, then pass the variables along to myProfile.php in order to use the following code:
myProfile.php:
<?php
$name = $_POST['name'];
$surname = $_POST['surname'];
$dob = $_POST['dob'];
echo "<h2>Your Input:</h2>";
echo "My name is " . $name . " " . $surname . ". I am " . date_diff(date_create($dob), date_create('today'))->y . " years old.";
?>
You should be able to use PHP's session functionality to do this. Sessions are not specific to PHP, but PHP has functions which make it easy to maintain data about a specific visitor. This can be tricky because HTTP is a stateless protocol.
In index.php, after you have made sure that the data is valid you can store it in session by calling session_start and using the superglobal $_SESSION variable:
if ($data_is_valid) // you'll have to figure out yourself whether data is valid or not
{
session_start(); // you must call this before using $_SESSION
$_SESSION["valid_data"] = array(
"name" => $name,
"surname" => $surname,
"dob" => $dob
);
// redirect the user to the other page
header("location: myProfile.php");
// always remember to exit after redirecting or code may continue to execute
exit;
}
Then, in my Profile.php, you can call session_start and check for the valid data
session_start();
if (!array_key_exists("valid_data", $_SESSION)) {
die("No valid data found!"); // you might want to redirect back to the first page or something?
}
$data = $_SESSION["valid_data"];
if (!is_array($data)) {
die("Data found is not an array!");
}
// otherwise, data was found...you can keep going!
// you might get errors here if you didn't set these properly on the the previous page
$name = $data['name'];
$surname = $data['surname'];
$dob = $data['dob'];
echo "<h2>Your Input:</h2>";
echo "My name is " . $name . " " . $surname . ". I am " . date_diff(date_create($dob), date_create('today'))->y . " years old.";

Failed to assign variable taken from database to json array

I try to get the data from database to display data via ajax but failed to worked. It's partially working because data from mysql make this thing failed to function.
Here is my funds_transfer_backend.php page. This page will assign variable to json array.
session_start();
if(!isset($_SESSION['myusername']))
{
header("Location: ../index.html");
die();
}
include("../connect.php");
$myusername = $_SESSION['myusername'];
$sql="SELECT client_id FROM `client` WHERE username='$myusername'";
$result=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_row($result)){
$id = $row['0'];
}
$index_num = $_POST['index_num'];
$to_account_num = $_POST['recipient'];
$amount = $_POST['amount'];
if ($amount == '' || $to_account_num == '' || $index_num == -1){
//echo "Please complete the form!";
$response = -1;
}
else {
// check account number exist
$query2 = "SELECT 1 FROM account WHERE id='$to_account_num' LIMIT 1";
if (mysqli_num_rows(mysqli_query($conn, $query2))!=1) {
//echo "Recipient account number is invalid!";
$response = -2;
}
else {
$query2 = "SELECT client.name, client.email FROM account JOIN client USING (client_id) WHERE account.id = '$to_account_num' LIMIT 1";
$result=mysqli_query($conn, $query2);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$name = $row['name'];
$email = $row['email'];
}
$response = 1;
}
} // check account num else bracket
$display = array('response' => $response, 'name' => $name);
echo json_encode($display);
However if I remove 'name' => $name from array the #stage div will trigger like image below:
Here is my funds_transfer.php page
<script type="text/javascript">
function update() {
var two = $('#index_num').val();
var three = $('#recipient_box').val();
var five = $('#amount_box').val();
$.post("funds_transfer_backend.php", {
index_num : two,
recipient : three,
amount : five
},function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
}
</script>
...other code goes here
<div id="stage" style="background-color:#FF6666; padding-left:20px; color: white;"></div>
<div id="confirm" style="background-color:#FF7800; padding-left:20px; color: white;"></div>
I try to check the data from db whether it exist using manual form method="post" and I can see the name being echo. Any help is appreciated and thanks in advance.
When your response is -1, your $name variable is undefined. So php could show a warning (depending on your settings) and you are trying to add an undefined variable to your array. This will invalidate your output / json.
You can set for example:
$name = '';
at the start of your script or check whether the variable is set with isset($name) before you try to use it to avoid these problems.
There are of course other solutions, like outputting your -1 directly and exiting the script there.
I always initialize my variables.
$myusername = isset($_SESSION['myusername']) ? $_SESSION['myusername'] : false;
Then you can safely do:
if ($myusername) {} without throwing warnings.
I do this weather I get my data from a db, post/get/session or json/ajax.
It takes a little extra time upfront but removes dozens of errors in the back end so you net more time.

Php Single page form processing issue

(Sorry for my bad english)
Well, I've 3 errors in my code.
Error's:
First of all it's show : Notice: Undefined index: form in C:\xampp\htdocs\evantechbd\index.php on line 461. When i run this form.
if any error found it's show error message, well, but correct field is empty. Example: In this form there is 4 fields. a) upload image, b) select discussion c) subject and d) message. Suppose you upload a image, select a discussion and write a subject but forgot to write message. Then It's show "Message Required" and every filed is empty. I don't want empty field which is correct.
After successfully submitted the form it's show "Discussion was submitted ". But after that if i refresh the page it's send the data to database. But I did not click submit button. why this happen?
Here is my code:
<?php
if ($_POST['form'] == "Submit") {
$err = array();
$filed = addslashes($_FILES['file']['tmp_name']);
$img_named = addslashes($_FILES['file']['name']);
$img_type = addslashes($_FILES['file']['type']);
#$imgd = addslashes(file_get_contents($_FILES['file']['tmp_name']));
function getExtension($str)
{
$i = strrpos($str, ".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str, $i + 1, $l);
return $ext;
}
$extension = getExtension($img_named);
$extension = strtolower($extension);
$image_named_uniq = uniqid() . '.' . $extension;
$upload_path_dis = 'user/manage/discussionimg/';
$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$date = "On " . date("F Y h:i:s A");
if (!isset($_SESSION['uname']))
$err[] = "You need to login";
else {
$uname = $_SESSION['uname']; //session username
if (empty($sub) && empty($msg) && empty($filed))
$err[] = "All field required";
else {
if (empty($sub))
$err[] = "Subject Requried";
if (empty($msg))
$err[] = "Message Requried";
if (empty($filed))
$err[] = "SORRY, you have to be upload a image";
}
}
if (!empty($err)) {
foreach ($err as $er) {
echo "<font color=red>$er</font><br/>";
}
}
else {
$sql = mysql_query("INSERT INTO discussion VALUES ('', '$imgd', '$image_named_uniq',
'$diss', '$sub', '$msg', '$uname', '$date' ) ");
if (!$sql)
echo "Can't submit your discussion" . mysql_error();
if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_path_dis . $image_named_uniq)) {
die('File Not Uploading');
} else {
echo "Discussion was submitted";
}
}
}
?>
Many Thanks for your help!!
Kanta.
Try changing your first if condition as follows
if (isset($_POST['submit']))
Now most of web sites uses client side validations using javascript. You can use jquery frame work to make things easier. However since you already uses validations after the POST event. You have to set values to relevant fields as bellow code. It will set tha value of the subject.
<input type="text" name="sub" value="<?php if(isset($_POST["sub"])) echo $_POST["sub"]; ?>" size="46"/>
Yes if you refresh the code it will again do the post and insert. You have to do few controls. However these things depend on your data.
a. Make unique key indexes in the database
b. Check for existing record before the insertion.
c. Redirect your page to the same page after few seconds once the user see the successful message.

Categories