Hi just looking for some direction, I have a HTML form which has several fields and basically what I am wanting to do is save the data entered from the form to a PHP config file and also have the ability to edit the saved data by accessing and submitting the form again. I would prefer to do this without the use of a database.
So here's an example:
<form method="post" name="config_form">
<div id="field">
<label>Keywords</label>
<br />
<input type="text" name="keyword">
</div>
<br />
<select name="color">
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
</select>
</form>
So the user enters 'computer' as the keyword and selects the color 'blue'. I want to then save this data into my config.php file as variables allowing my other website pages to access this data. Should this all be in an array as well?
<?php
//config file
$keyword = "computer";
$color = "blue";
?>
Also when I go back access the form again can I make it so the fields are prefilled with the data from the config.php file?
Any help would be much appreciated thank you!
If you're dedicated to storing this sort of thing in a file, then probably the easiest way is to just store all the data in an array in the form of $keyword => $value then use the serialize() and unserialize() functions to transform them into a format that can be easily stored into and read from a file.
Keep in mind that if there is only one file, then a change made by one user will affect them all, so if that's not acceptable, then you'll need to come up with a way to determine the user and which file to use.
A much better way of doing this is to just store these values in a database. Create a table called options with two fields - option and value - which will store the configuration options. If you want different users to have their own options, then you could add another field - userid (as a foreign key to a users table) - to track which user an option pair applies to.
Further, if there are a predefined set of options a user can set, then you could have fields in the table for each option, with default values, and you can create a row for each user with the specific config options set in a single record for that user.
You can include your configuration file in your main php script file:
// main.php
<? php include("config.php"); ?>
and build the form with something like this:
// main.php
<?php
?>
<form method="post" name="config_form">
<div id="field">
<label>Keywords</label>
<br />
<input type="text" name="keyword">
</div>
<br />
<select name="color">
<option value="green" <? if ($color == "green") echo "SELECTED"; ?> >Green</option>
<option value="orange" <? if ($color == "orange") echo "SELECTED"; ?> >Orange</option>
<option value="blue" <? if ($color == "blue") echo "SELECTED"; ?> >Blue</option>
<option value="red" <? if ($color == "red") echo "SELECTED"; ?> >Red</option>
</select>
</form>
<?
?>
finally you can save the form data in your config.php file using fopen() and fwrite() functions on form submit:
$key = $_POST["key"];
$color = $_POST["color"];
if ($key != '' && $color != '') {
$f = fopen('config.php', 'w') or die("can't open file");
fwrite($f, '<?php $keyword=' . $key . ';$color=' . $color . ';?>');
fclose($f);
} else { // write default values or show an error message }
You can do this in multiple ways. Best way would be to use a database such as MYSQL. You are asking for persistence and that is what DBs are for. Try this.
$key = $_POST["key"];
$color = $_POST["color"];
mysql_query("INSERT INTO smeTbl VALUES ('1',$key,$color)");
THen in the config file or what ever other file you have you can retrieve these values.
$query = mysql_query("SELECT * FROM smeTbl WHERE id='1'");
$fetch = mysql_fetch_array($query);
$keyword = $fetch["key"];
$color = $fetch["color"];
This is just an example and you can refine it based on your needs
when you submit the form and you want to store the submitted form's data in one php file,ni must use the file action functions fopen the config.php,and write php code into it.
when you display the form,you can fopen the config.php,and use the function "eval" to get data.forgive my english.
//when submit form
$string = '<?php $keyword="computer";$color="blue";?>';
$fp = fopen('config.php', 'w');
fwrite($fp, $string);
fclose($fp);
//when display form
include("config.php");
//so you can use $keyword and $color
Related
Once I add session in edit form, I could not get selected values in dropdown menu. I am using bootstrap framework. When I remove session from the same beginning it works.
edit.php file
<?php
session_start();
$car=$_POST['car']
?>
<form method="post" action="">
<div class=from-group>
<label for="exampleInputEmail1>Car</label>
<select class="form-group" name="car" id="car" value="<?php echo $car; selected?>">
<option value=<?php echo $car?> selected>
<?php cars()?>
</option>
</div>
</form>
I have created "cars" function in which I get values of all cars from database.
function cars(){
$link = new mysqli("", "", "", "");
$link = set_charset("utf8);
$sql = mysqli_query($link, "SELECT * FROM db_cars ORDER BY CarId")
echo '<option value=""> Choose car </option>'
while ($record = mysqli_fetch_array($sql)) {
echo '<option value = "'.$record['CarId']'"> . $record['CarName'].' </option>
}
}
Any help or advice is appreciated.
The select element has no name attribute, so it cannot be a successful control (i.e. submit any data).
The form has no submit button, so there is no obvious way for you to trigger the form submission. (You have to submit the form in a new HTTP request to the server to run the PHP and get the data from the user).
First, add the semicolons after every line when you use PHP. That can make a lot of troubles.
Second, some attributes have just one ("), like the label in the HTML.
Third, you are adding "something" called selected after echoing $car.
In the function cars() you are echoing without a semicolon (;) and just after doing a while() loop.
Check out all, you are missing very important and essential things
Also, I gonna guess this is not a "copy-paste" from your code, but if it's, you also are missing </select>
iamiI have a selection tag and and options that can do task in the page , but the problem is that it just does that in just the index page and not and the others... this is my code:
region.php
(isset($_POST["company"])) ? $company = $_POST["company"] : $company=1;
if(isset($_POST['selectedRegion'])){
$region = explode( "|" ,$_POST['selectedRegion']) ;
$_SESSION['regCode'] = $region[0];
$_SESSION['selection'] = $region[1];
$regionCode = $_SESSION['regCode'];
}else if(isset($_SESSION['regCode'])){
$region[1] = $_SESSION['selection'];
$regionCode = $_SESSION['regCode'] ;
}else{
$regionCode = 'DEF';
$_SESSION['regCode'] = $regionCode;
}
<form id="regionSelect" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" onchange="this.form.submit();" >
<select id="selectedRegion" name="selectedRegion" size="1" autocomplete="off">
<option style="border-bottom: 1px dashed #000" value="<?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != 'DEF'){ echo "".$_POST['selectedRegion']."";}?>" selected="selected"><?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != "DEF"){ echo "".$region[1]."";}else{echo "--------";} ?></option>
<option value="ny">New York</option>
<option value="miami">Miami</option>
</select>
<input type="submit" value="Enter Region" />
</form>
process.php
<?php if(!isset($_SESSION)){ session_start();}
if(isset($_POST['selectedRegion'])){
$region = $_SESSION['selectedRegion']=$_POST['selectedRegion'];
if($region == "ny"){
echo "new york selected";
}
if($region == "miami"){
echo "miami selected";
}
?>
The index.php and all the other pages of the site have the region.php and the process.php included, but my problem is that any time that i do a selection it just does the action on the page that is in... and if i want the action to be made in another page i would have to press the option again. is there anyway that i can do the action of my selection work on page change and all the pages of my site? thanks
The solution you are looking for consists of these steps:
you evaluate the selection you receive at session start from the client, according to what the user has chosen. So just what you have so far.
you store that selection in a session variable. See the php documentation for the basic use of a session variable. It just boils down to:
session_start();
$_SESSION['region'] = $_POST['selectedRegion'];
you create a switch statement based on that session variable in all scripts that should react on that user choice:
session_start();
switch ($_SESSION['region']) {
case 'ny':
// do something
break;
case 'miami':
// do something
break;
default:
// do something
}
With this the user has to make his choice only once inside a single session (returning requests). You can offer that selection on the entry page and/or on all pages, just as you like. You can enhance that by storing that inside a persistent user profile, if you have an account management.
In addition some more information, as a reaction to your additional information as you provided by editing your question.
Your general approach is probably into the right direction, great. There are a few issues you have to correct though. I can only hint to them, since you offer only snippets of your scripts.
In 'process.php' you have this line:
$region = $_SESSION['selectedRegion']=$_POST['selectedRegion'];
This is obviously invalid syntax, you cannot have two assignments inside a single statement. At least that does not do what you want it to.
not sure if this conditional really belongs there:
if (isset($_POST['selectedRegion']))
It is fine if 'process.php' is the script meant to SET the session variable. In all other scripts obviously $_POST['selectedRegion'] is not set, since the user did not make a choice / was not offered a choice. So there you cannot test or use that variable, you just use the session variable directly.
there are a few other things, but as said you are on the right track.
This approach does work, it is the "normal" approach to this. So don't get frustrated, you will sort this out. In general: your code is a little confusing, too many separate variables where it is unclear what purpose they save. Why the distinction between region, regionCode and selectedRegion. Why isn't a single variable sufficient? Try to simplify your code, this will help to get this to work.
Value of $_POST['selectedRegion'] will not be available always. You should store this value in session like $_SESSION['selectedReg']=$_POST['selectedRegion']; during the form submission.
<form id="regionSelect" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" onchange="this.form.submit();" >
<option style="border-bottom: 1px dashed #000" value="<?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != 'DEF'){ echo $_SESSION['selectedRegion'];}?>" ><?php if (isset($_SESSION['regCode']) and $_SESSION['regCode'] != "DEF"){ echo $_SESSION['selectedRegion'];}else{echo "--------";} ?></option>
<option value="ny">New York</option>
<option value="miami">Miami</option>
</select>
<input type="submit" value="Enter Region" />
</form>
I've been working on a PHP form that changes values in a file on my server. The form changes the values correctly but I need the <option value="round" <?php if($shape == 'round'){?>selected="selected"<?php }?>>Round</option> part of the form to always show to current value that is set in the file, currently it does not.
#file contents (the lines the values are on changed on a regular basis)
size=large
color-name=red
shape=round
height=short
weight=heavy
<?php
$file = "/home/user/color.props";
$contents = file($file, FILE_SKIP_EMPTY_LINES);
foreach($contents as $line) {
list($option, $value) = explode('=', $line);
if ($option == 'color-name') {
$color_name = $value;
} elseif ($option == 'shape') {
$shape = $value;
}
}
if(isset($_REQUEST['color_choice'])){
exec('sed -i '.escapeshellarg('s/color-name=.*/color-name='.$_REQUEST['color_choice'].'/g')." /home/user/color.props");
echo 'Color setting has been updated';
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="color_choice">;
<option value="round" <?php if($shape == 'round'){?>selected="selected"<?php }?>>Round</option>;
<option value="square" <?php if($shape == 'square'){?>selected="selected"<?php }?>>Square</option>;
</select>
<input type="submit" name="Submit" value="Submit" />
</form>
I'm still unclear on what exactly you're trying to accomplish. Your current code is only saving the last 'color-name' and 'shape' objects being read in from the file. It then can configure the selected option by making this change:
<option value="red" <?php if($color_name == 'red'){?>selected="selected"<?php }?>>Red</option>;
<option value="blue" <?php if($color_name == 'blue'){?>selected="selected"<?php }?>>Blue</option>;
<option value="green" <?php if($color_name == 'green'){?>selected="selected"<?php }?>>Green</option>;
<option value="purple" <?php if($color_name == 'purple'){?>selected="selected"<?php }?>>Purple</option>;
NOTE: The way you're reading in the file appends carriage returns/line returns at the end of your variables...for example, $color_name on my end contains two extra hex values at the end of the string: x0d and x0a
EDIT #2: Try making your form like this:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select id="color_choice">
<option id="round">Round</option>
<option id="square">Square</option>
</select>
<input type="submit" name="Submit" value="Submit" />
</form>
<script>
var option = document.getElementById("color_choice");
option.options['<?php echo $shape ?>'].selected = true;
</script>
I'm pretty sure this will work, changes I made were:
1) Using javascript instead of php to change selected
2) Using id attributes instead of value or name
3) Added <script> tag at the end of form (it may not work if it's before)
You'll have to make changes to the form and the script depending on what type of values you're pulling from the file...but you should be able to figure out how to handle that.
I currently have an HTML file, with a form in it, that when submitted POSTs the form & calls a simple short PHP file that calls a function within another PHP file using the POSTed variables as parameters. The files are both below. What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
Ideally, this would set the call to the function:
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
as the form action. Does anyone know how/if this can be achieved?
HTML:
<FORM ID="FORM1" METHOD="POST" AUTOCOMPLETE="off" ACTION = "writeToDL.php">
<INPUT TYPE="hidden" NAME="Date" STYLE="WIDTH:0px; " MAXLENGTH="8" TITLE="Enter Date" Value="<?php $dt = date('Y-m-d'); echo $dt ?>"/>
<INPUT TYPE="text" NAME="Time" STYLE="WIDTH:70px; " MAXLENGTH="7" ONCHANGE="validateTime();" />
<SELECT NAME = "Result">
<OPTION VALUE = OK></OPTION>
<OPTION VALUE = C>C</OPTION>
</SELECT>
<SELECT NAME = "Participant" STYLE = "WIDTH: 187">
<OPTION SELECTED VALUE = "">Select...</OPTION>
<?PHP
$allParticipants = getall_participants();
foreach($allParticipants as &$value) {
$val = $value->get_id();
echo "<OPTION VALUE='",$val,"'>";
echo $value->get_first_name()," ",$value->get_last_name();
echo "</OPTION>";
}
?>
</SELECT>
<TEXTAREA NAME='Notes' COLS='28' ROWS='5'></TEXTAREA>
<INPUT TYPE="image" SRC = "images/submit.png" VALUE="Submit Participant"/>
</FORM>
PHP File:
<?php
include_once('database/PE.php');
insert_PE(new PE($_POST[Date],$_POST[Participant],$_POST[Time],$_POST[Result],$_POST[Notes]));
?>
You COULD do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include_once('database/PE.php');
insert_PE(new PE($_POST['Date'],$_POST['Participant'],$_POST['Time'],$_POST['Result'],$_POST['Notes']));
} ?>
<html>
... rest of your page here ...
</html>
That way the PHP code only fires if an POST was actually performed. Some would suggest checking for the presence of a form field, but that's unreliable - you might change the form down the road and forget to update the if(). Checking the request method is guaranteed to be 100% reliable.
What I am wondering is whether I can somehow skip the middleman PHP file, and simply call the function from my HTML file.
No. The client only knows about URIs.
A URI can map to a PHP program. Multiple URIs can map to the same PHP program. You can use logic to determine what functions to run for a given URI. You can't avoid having that logic in your program.
One option is to put method="_the_main_php_file_containing_function_to_be_called_"
I hope it works fine.
I think you could use a hidden field on the form, and populate it with the name of the function you want to run on "destination.php". Then a switch statement on "destination.php" could pull the name of the function from POST variable.
I want the user to be able to pick two different variables from a website (from a drop down menu) and hit a button to bring them to a page where files are to download based on the variables picked.
I have the html ready to go.. and i have both menus in an array in php.. i was wondering how to pass both variables through to another site and then have unique content depending on which ones picked..
how do i get php to make it's own site?
Try something like this:
page1.php
<?php
$ar = array('foo', 'bar');
?>
<form action="page2.php" method="post">
<select name="choice">
<?php foreach($ar as $value) { ?>
<option value="<?php echo $value ?>"><?php echo $value ?></option>
<?php } ?>
</select>
<input type="submit" value="go to page2">
</form>
page2.php
<?php
$choice = $_POST['choice']; // sanitize as needed
if( $choice === 'foo' ) {
// do foo choice
}
else if( $choice === 'bar' ) {
// do bar choice
}
?>
Query strings are also ok, just change the form method to GET, and $_POST to $_GET.
have you tried using query variables? og perhaps posting the info to the page?
I would suggest using the query like: http://www.yourdomain.com/speciallayoutpage.php?layout=2&colortheme=1