How to use PHP global variable for 2 functions? - php

I'm trying to create an interface where a workshop description can be updated on the server after it has been created by a user. There is a text field and a button that brings up the workshop by the number it was assigned. (This is also the name of the directory in the submissions/workshop# on the server). When I set the variable $workshopPath using this method, I want to be able to access this global variable when a text input is filled out with the string to update the title of the workshop. The $workshopPath is registering as an empty string in the 'updateTextItems' function, so it is writing the text file to the root directory instead of to the correct workshop directory. I thought I was correctly referencing the global variable within the functions, but this isn't working. I also tried using $GLOBALS['workshopPath'], but that isn't working either. Can someone help me figure out how to pass the variable to the second function? Thanks :-)
<?php
$workshopPath;
if (isset($_POST['gotoWorkshop'])) {
if (empty($_POST['numberInput'])) {
echo "Please enter a valid workshop number";
} else { //Assign the name variable form the posted field info if one was entered.
$workshopNumber = stripslashes($_POST['numberInput']);
global $workshopPath;
$workshopPath = "submissions/" . $workshopNumber . "/";
}
}
if (isset($_POST['updateTextItems'])) {
if ($_POST['titleInput']) {
//Assign the name variable form the posted field info if one was entered.
$titleInput = stripslashes($_POST['titleInput']);
}
if ($titleInput) {
global $workshopPath;
$titleFile = fopen($workshopPath . "title.txt", "w") or die("There was an error creating the title file.");
fwrite($titleFile, $titleInput);
fclose($titleFile);
}
}
?>

Do I understood you correct? The user fill in the a form for the workshop click submit and get an othewr form for the text? My guess is you sen to requests to the server. So $GLOBAL will not work for you. It only works per request and I think most time you do not realy need it. If you want to save some values across requests, you need a session when you start your session. After you have started your session with session_start() you can use $_SESSION[] to store and get your value

Related

WordPress Wedding RSVP using Gravity Forms

I am building my wedding website and want to integrate an RSVP form using Gravity Forms. The issue I am running into is how to set certain guest that have +1's. I would like to show an additional guest entry (First Name, Last Name, Meal Option) when the initial First Name and Last Name has been populated. How would I go about doing this? Any help would be great! Thanks in advance!
Here is how I'd solve this problem:
First, you need to put everything in the DB, the easiest way would be to either do it manually or somehow loop through an array/CSV calling add_option($key, $value) Again, I would recommend a mobile/phone number as they'll be unique so you don't pull the wrong "John Smith". I'll assume you'll keep it basic with $key as the unique identifier and $value as boolean as to whether to show additional info. Interestingly, by default, if not found get_option($key) will return false and therefore not show your additional data, which I would assume you'd want anyway. If you'd rather it return true just pass true as the second argument.
Now for your answer:
Your URL is something like https://somesite.com/rsvp?id=1234.
function allowed_plus_one() {
$id = $_GET["id"];
$allowed = get_option($id);
return $allowed;
}
Then assumedly it'll be something like
if (allowed_plus_one()) {
// show form with plus one
} else {
// show form without
}
EDIT:
Keeping separate incase this has already been viewed.
You should also be checking for the existence of $_GET["id"] and behaving accordingly. eg:
if (isset($_GET["id"] && !empty($_GET["id"]) {
//do logic above
} else {
//here by mistake so don't show any form?
}

How to get value of Shortcode when its appended to URL and Stored in Database

I stored the url in Database
https://example.in/register/?ref=[affiliate_id]
and I tried to get the affiliate id of current logged in user.But I am unable to get the value when I print it.
But if I used as directly like using
$val = do_shortcode('[[affiliate_id]');
I am getting the value.
Please solve my issue
I am not sure but use below code it might be resolved your problem
add_action('init','runShortcode');
function runShortcode(){
$getCode = $_request['ref'];
If($getCode)
{
$shirtcodes = '['.$getCode.']';
echo do_shortcode($shirtcides);
}
Not sure with code

PHP: Delete Value of variable after 5 min

I have problem in print PDF from forms.
When new user go to my site and fill the forms and click submit to send data, i need to get this data in PDF file, So i can get the data for this user from :-
$lastid = mysql_insert_id();
But this i think is not good, When any other user go in this form and click print PDF, he get the last id.
So what can i do to delete the last id and cannot print any data for any user else have fill forms ??
I assume that you are getting data into $lastid because of mysql query execution if that so your query will be executed every time and the result will change depending upon users and their requirement.
But if you still want to do so you can use unset() function of php.
unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
To unset() a global variable inside of a function, then use the $GLOBALS array to do so:
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar = "something";
foo();
?>
Complete documentation can be found over here

How to make a webpage retain variables from form?

Sorry if I'm duplicating threads here, but I wasn't able to find an answer to this anywhere else on StackOverflow.
Basically what I'm trying to do is make a list in which variables entered in a form by a user can be kept. At the moment, I have the code which makes this possible, and functional, however the variables entered in the form only appear on the list after the user hits submit... As soon as I refresh the page or go to the page from somewhere else, the variables disappear. Is there any way I can stop this from happening?
Edit: here are the codes:
//Page 1
<?php
session_start();
$entries = array(
0 => $_POST['signup_username'],
1 => $_POST['signup_email'],
2 => $_POST['signup_city']);
$entries_unique = array_unique($entries);
$entries_unique_values = array_values($entries_unique);
echo "<a href='Page 2'>Link</a>";
$_SESSION['entries_unique_values'] = $entries_unique_values;
?>
//Page2
<?php
session_start();
$entries_unique_values = $_SESSION['entries_unique_values'];
foreach($entries_unique_values as $key => $value) {
$ValueReplace = $value;
echo "<br /><a href='http://example.com/members/?s=$ValueReplace'>" . $value . "</a><br/>";
}
?>
Your question is really quite vague. the answer depends on how much data you have to store, and fopr how long you need it to exsist.
By variable I assume you mean data the user has entered and that you want to put into a variable.
I also presume that the list of variables is created by php when the form is submitted.
Php will only create the variable list when the form is submitted as php is done entirely on the server, therefore you will not have or see the variables until the form is submitted.
if you wanted to be able to see the list as it is being created you could use javascript then once you have you php variables the javascript list isn't necesary.
each time you request a php page wheather it is the same one or not the server generates a totally new page, meaning all unhardcoded variables from previous pages will be lost unless you continually post the variables around the pages the server will have no memory of them.
You have a few viable options.
) keep passing the user created variables in POST or GET requests so each page has the necesary info to work with. Depending on the situation it might or might not be a good idea. If the data only needs to exsits for one or two pages then it is ok, but bad if you need the data to be accessable from any page on your web.
2.) start a session and store the variables in a session. Good if the data only needs to be around while the user is connected to the site. but will be lost if user close window or after a time.
3.) place a cookie. not a good idea but ok for simple data.
4.) create a mysql database and drop the variable info in there. great for permanent data. this is how i always complex user data.
just a few ideas for you to look into as it is difficult to see what you really mean. good luck.
use PHP session or store variable values in Cookies via JS or using PHP. It would be nice if you show your working codes :)
Your idea is fine, however you just need to add a little condition to your Page 1 that only set your SESSION values when POST is made, that way it will keep the values even if you refresh. Otherwise when you visit the page without a POST those values will be overwritten by blank values, which is what you are seeing now. You can modify it like
<?php
session_start();
if(isset($_POST["signup_username"]))
{
$entries = array(
0 => $_POST['signup_username'],
1 => $_POST['signup_email'],
2 => $_POST['signup_city']);
$entries_unique = array_unique($entries);
$entries_unique_values = array_values($entries_unique);
$_SESSION['entries_unique_values'] = $entries_unique_values;
}
echo "<a href='http://localhost/Calculator/form2.1.php'>Link</a>";
?>
You could use JavaScript and HTML5 local storage.

I am making a form that includes city and email and a submit button and I need help on how I connect this to a database

I am having a difficulty of finding a answer that is simple to follow and understand... I making a site (on dreamweaver cs5) and the frontpage of the site has a select city and a dropdown of all the major cities and a email text box.
I have a few questions and those are as follows:
What is my next step now that I have the html pretty much done... do I connect it to a database?
What php script would I need to make sere both fields (the city and email) are filled? and where would I enter this php script?
Here is some of my code in case you were wondering:
http://answers.yahoo.com/question/index?qid=20110611111223AAeAnrT (had to put it on here because overflow wouldn't let me put in code..)
Just a quick starter, to get your form up.
On creating your PHP script, I don't know much about Dreamweaver, but if you have PHP installed on your server, you should be able to create it in the same directory as your HTML. All of the form elements should be in a form tag, and should point to the PHP, such as <form method="POST" action="dosomething.php"> before and </form> after.
Also, a "Please select your city..." might be nice to have on the form, like <option value="unset">Please select your city...</option>. (Also, all of the options in the sample should have a value attribute).
I don't know how much you have learned about PHP, so I'm going to try to start with the basics. The PHP script would be a plain-text file with the extension .php, such as dosomething.php. Inside of the script, the PHP code needs to be surrounded by the PHP start and end tags, <?php and ?>.
The values inputed into the form should be accessible with the $_POST variables in PHP, so in the script $_POST['select'] will be set to the current value. I recommend setting the names to something you can remember, such as selectedCity and emailAddress.
In our PHP script, we will want to get the variables from our form, and check to see if they are both filled. Then the data will get written to the database. I have created a sample snippet below that is commented, but extra security should be added, and this code should not be used as-is.
<?php
$city = $_POST['selectedCity']; // Get the city the user selected from the form
$addr = $_POST['emailAddress']; // Save the email address the user entered
if($city == "unset")
{
// Stops user if a city hasn't been selected
die("Please select a city."); // Stop executing code, and tell user to go back and select a city
}
if($addr == "")
{
// Stops user if the email address is blank (also would be good to make sure email address is correct, like user#domain.com)
die("Please enter a valid email address");
}
if(!file_exists("../mailinglist.sqlite"))
{
// Creates the database if it doesn't exist
// The database should be outside the document root (meaning you can't access it through the web)
$db = sqlite_open("../mailinglist.sqlite"); // Opens the database, creates it if non-existent (it is)
sqlite_query("CREATE TABLE users (city, email)"); // Creates a table for users
}
else
{
$db = sqlite_open("../mailinglist.sqlite"); // Opens the database if it exists
}
sqlite_query("INSERT INTO users (city, email) VALUES ('".sqlite_escape_string($city)."','".sqlite_escape_string($city)."')"); // Add the new user to the database
?>
(Anything that you need help with that is in blue should be searchable on the PHP Documentation)
The code above will take the output from the HTML form, check to make sure that it is not empty, and enter it into a database, creating a new database if it does not exist. Again, this is just a starter, and the code needs to be improved before taking it live.
Hope this helps!

Categories