It seems my code is correct, however the posted variables in the form will not echo in the update user settings page in the form. I have echoed the posted ids from the input in the database but I cannot get the variables to show.
I have done this in Codeigniter fine but am trying to do it in pure php with my own framework.
$users = new Users($db); comes from my init.php file that is called at the beginning of the file below.
when I
<?php var_dump($user['first_name'])?>
I get Null
<input type="text" name="first_name" value="<?php if (isset($_POST['first_name']) )
{echo htmlentities(strip_tags($_POST['first_name']));} else { echo
$user['first_name']; }?>">
Hoi Stephen,
Try print_r($_POST["first_name"]); instead of var_dump();
or just for all:
print_r($_POST);
best regards ....
add this at the top of your html page
#extract($_REQUEST);
and put is just to check and after checking remove the below line
print_r($_REQUEST);
hope this help .
Related
I have a site based on wordpress. I need to allow people to create posts from frontend so I have made a multi-part form which works pretty well. There are three parts of the form and each part of the form is validated before moving to the next part. Data is passed to another page through hidden inputs.
My form template looks somewhat like this ( complete code is pretty massive and irrelevant here, so just showing just the relevant parts ) which I hope is enough to give an idea how the form works.
MULTI-PART FORM WP-TEMPLATE SAMPLE CODE :
<?php
global $wpdb;
$this_page = $_SERVER['REQUEST_URI'];
$page = $_POST['page'];
if ( $page == NULL ) { ?>
<?php include_once('multiparts/form-files/first_part.php'); ?>
<?php } else if ( $page == 1 ) { ?>
<?php include_once('multiparts/validation/validate_first_part.php');
if (isset($_POST['submit-1']) && (!empty($error))) { ?>
<div class="error-head">Cannot continue registration. Error/s highlighted below.</div><br/>
<?php echo $error . '</br>'; ?>
<?php } else {
include_once('multiparts/form-files/second_part.php');
}
?>
<?php
} else if ( $page == 2 ) { ?>
//SO ON AND SO FORTH
<?php
}
?>
Recently, I have a added several checkbox fields in the form with an intention to display values of selected checkboxes, in the created posts. So here is a relevant html form code that I am currently using.
<fieldset class="work-areas">
<label for="areas" class="label">INTERESTED IN :</label></br>
<div class="work-class">
<input type="checkbox" name="workareas[]" value="administration"/>administration</br>
<input type="checkbox" name="workareas[]" value="technical"/>technical</br>
<input type="checkbox" name="workareas[]" value="creative"/>creative</br>
<input type="checkbox" name="workareas[]" value="fieldwork"/>fieldwork</br>
<input type="checkbox" name="workareas[]" value="marketing"/>marketing</br>
</div>
</fieldset>
I insert the values of these checkboxes into the post just like any other custom fields using this code: add_post_meta($pid, 'areas', $workareas, true );. In the processing part it is assigned a meta_key areas. I display it in the single.php with the code below :
<?php $areas = get_post_meta($post->ID, 'areas', true); ?>
<?php if (is_array($areas)) : ?>
<h4>INTERESTED AREAS OF WORK:</h4>
<?php if (is_array($areas)) {
foreach($areas as $area) {
echo '<li>'.$area.'</li>';
}
}
?>
<?php endif;?>
ISSUE: All this works well when the above given html form code for checkboxes is in the last/third part of the form. But it does work when the same checkbox fields is in the second part of the form. I guess it simply does not pass the array values of the selected checkboxes to the third part. Print_r shows an empty array and obviously does not display anything in the single.php too. Although I understand that the trouble is just the array of selected checkbox values, NOT being carried to the third part properly, I need help as I am noob to all this.
So the bottomline question is how do I save the array of the selected
checkboxes' values in the second part and carry it to the third part
and finally assign it to a variable which will hold the array values.
That which can be displayed in post using the code above.
THINGS TRIED : I have looked into this thread here and I am confused where I will insert my checkbox fields and not even sure it applies to my situation. I have been able to pass other text input values from one part to another part of the from using something like this :
<input type="hidden" name="eligible" value="<?php echo $eligible;?>" />
So, I tried using name="workareas[]" but did not work. I am doing print_r() for everything I am trying and till now have only been getting empty array. I am still going through tons of other threads looking for possible hints. In the meanwhile if you can help, that will be great. Thanks in advance.
UPDATE : Solved, please check the answer.
Not a WP user but your checkboxes are named "workareas" but you seem to refer to them as "areas" everywhere else.
Thanks for the suggestions in the comments but I have found a graceful and robust solution in my opinion, that is using sessions. I followed the basic idea from here which actually deals with a multipart form with sessions. Now I have the following code in my third/last part of the form, at the very beginning of the document. At this time please remember that the html checkbox fields as illustrated above in the question are in the second part.
<?php
session_start();
$_SESSION['workareas'] = $_POST['workareas'];
$result=$_POST['workareas'];
?>
The code is that is repeated during the validation of the third part is the same but this way the variable $result is still holding the values of the array of the selected checkboxes from the second part of the form.
session_start();
$result=$_SESSION['workareas'];
You can do a print_r($result) at this point and check. Furthermore, if you want to insert these array values to post in order for them to show up in the post just assign meta_key eg. areas to $result and use the code below to add it as a custom field :
add_post_meta($pid, 'areas', $result, true);
In the single.php you can use the code below to pull values from the array and show. Do not avoid if(is_array) statement else wordpress might throw an error warning: invalid arguments supplied foreach(). Goodluck.
<?php $areas = get_post_meta($post->ID, 'areas', true); ?>
<?php if (is_array($areas)) : ?>
<h4>INTERESTED AREAS OF WORK:</h4>
<?php if (is_array($areas)) {
foreach($areas as $area) {
echo '<li>'.$area.'</li>';
}
}
?>
<?php endif;?>
I have faced a problem in all of my php projects is that since i used OOP is that if there is a user submitting a form
when it goes to processing it and if it has an error i save a message in the session and redirect them to the same page
this is a sample and of course when it redirects it wipes all the fields that was there
like let's say i have a register form that had
<?php if(!empty($message)) { echo $message } ?>
<form action ="forms/register.php">
first name: <input type="text" name="first_name" />
username:<input type="text" name="username" />
<input type="submit" value = "submit" />
</form>
and this is what the code in forms/register.php
if(isset($_POST['submit'])) {
$first_name = $_POST['first_name'];
$username = $_POST['username'];
if(empty($first_name) || empty($username) {
$session -> message("please fill in all the fields");
redirect("../register.php");
} else {
// do something else like insert query
}
}
my problem is if first_name or user_name is empty and it redirects to register.php
and it echos the error message no problem in that
but the fields are empty the first_name and the user_name are empty
so the user has to fill it all again
so one of my friends suggested to save it in the session or something
so i would like to know if that is possible then how and what i mean by how so nobody would get it wrong, i mean the way not the code to just copy it and paste it
Thanks in advance
and sorry for being long and annoying
You can store whatever values you want to keep persisted in the form after the page redirects in session variables, then retrieve those values on the form page and echo them in the value attribute of the form elements.
session_start(); $_SESSION['nick'] = $_GET['nick'];
more / better examples:
http://php.net/manual/en/function.session-start.php
Not sure what issue you exactly are facing (also what $session is inside your workflow?).
However, i recommend using PHP inbuild session support.
http://php.net/manual/en/features.sessions.php
From the above link itself:
<?php
session_start();
if(isset($_SESSION['views']))
{
$_SESSION['views']=$_SESSION['views']+1;
}
else
{
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
}
?>
Above code simply keeps track of page views. $_SESSION variable persists between page loads and you should be using the same for all your session requirements.
I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
Something like
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
Bit of a new thing for me with php, any help greatly appreciated :)
Thanks
You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
Do it like this:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
For validate the field param you may write like this:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.
I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>
I'm new to forms and post data ... so I don't know how solve this problem!
I've a php page (page1) with a simple form:
<form method="post" action="/page2.php">
<input type="search" value="E-Mail Address" size="30" name="email" />
<input type="submit" value="Find E-Mail" />
</form>
How you can notice ... this form post the 'email' value to the page2. In the page2 there is a small script that lookup in a database to check if the email address exist.
$email = $_POST['email'];
$resut = mysql_query("SELECT * FROM table WHERE email = $email");
.
.
.
/* do something */
.
.
.
if($result){
//post back yes
}
else{
//post back no
}
I don't know how make the post back in php! And how can I do to the post back data are read from a javascript method that shows an alert reporting the result of the search?
This is only an example of what I'm trying to do, because my page2 make some other actions before the post back.
When I click on the submit button, I'm trying to animate a spinning indicator ... this is the reason that I need to post back to a javascript method! Because the javascript function should stop the animation and pop up the alert with the result of the search!
Very thanks in advance!
I suggest you read up on AJAX.
Here's a PHP example on W3Schools that details an AJAX hit.
Hi i think you can handle it in two ways.
First one is to submit the form, save the data in your session, check the email, redirect
back to your form and display the results and data from session.
Like
session_start();
// store email in session to show it on form after validation
$_SESSION['email'] = $_POST['email'];
// put your result in your session
if ($results) {
$_SESSION['result'] = 'fine';
header(Location: 'yourform.php'); // redirect to your form
}
Now put some php code in your form:
<?php
session_start();
// check if result is fine, if yes do something..
if ($_SESSION['result'] == 'fine) {
echo 'Email is fine..';
} else {
echo 'Wrong Email..';
}
?>
More infos : Sessions & Forms
And in put the email value back in the form field
<input type="search"
value="<?php echo $_SESSION['email']; ?>"
size="30"
name="email" />
Please excuse my english, it is horrible i know ;)
And the other one the ajax thing some answers before mine !
As a sidenote, you definitly should escape your data before using it in an SQL request, to avoid SQL injection
As you are using mysql_* functions, this would be done with one of those :
mysql_escape_string
or mysql_real_escape_string
You would not be able to post in this situation as it is from the server to the client. For more information about POST have a look at this article.
To answer your question you would want to do something like this when you have done your query:
if(mysql_num_rows($result)){ //implies not 0
$data = mysql_fetch_array($result);
print_r($data);
}
else{
//no results found
echo "no results were found";
}
The print_r function is simply printing all the results that the query would have returned, you will probably want to format this using some html. $data is just an array which you can print a single element from like this:
echo $data['email'];
I hope this helps!
<?php
echo " alert('Record Inserted ');"
OR
echo " document.getElementByID('tagname').innerHtml=$result;"
?>
OR
include 'Your Html file name'