if($_POST)
{
if(array_key_exists("item_id", $_POST)) // asking if the array exists in data.php,
{
$item_ids = $_POST["item_id"]; // temp var. to hold the data.php data
$price=0;
foreach ($items as $item)
{
foreach($item_ids as $value)
{
if($value==$item['id']) //checking for the ids that were store in array
$price+=$item['price']; // adds price of the ids that are selected
}
}
require_once("view_confirm.php"); //shows the total of price in the view_confirm.php
die();
//if there wasnt any selected boxes its set to true for a statement to be stated on view_items
}
$error_no_items_selected =true;
}
My function works, I have a problem displaying an error message when the there is no click boxes, I set the value to false above post, $error_items_selected, on my view_items.php is HTML code, where I also use:
<?php if(error_items_selected==true){echo "Click Something";}
every time I refresh the page the message already appears,
In
if(error_items_selected==true){echo "Click Something";}
error_items_selected should have a $ if it's a variable.
Or () if it's a function call.
If you use error_items_selected - PHP considers it a constant. And if you don't have such constant, that is obvious, error_items_selected is considered a 'error_items_selected' string which is definitely true.
So proper way should be:
if ($error_items_selected==true){echo "Click Something";}
Also in first code block you use $error_no_items_selected. Maybe it's just different variables, but still - check them.
Related
I have an HTML form with PHP error checks. The form has several different types of fields (one for name, email, phone number, a checkbox, a drop down, etc.) and I have a PHP function written for each that runs when you hit the submit button, and checks that the form is filled in correctly and fully. If a field is left empty, or is filled in incorrectly, an error message appears. However, after I got that running, I tried to add a redirect, so that after the form is completed and submit is pressed, it brings the user to a confirmation page, if the errorchecks are passed. I wrote it like this:
if(isset($_POST['submit']) ){
header("Location:confirmed.php");}
It does what it's supposed to--bring the user to a new page--but it doesn't take into consideration any errorchecks. So, when submit is pressed, rather than run through the error checks, it immediately goes to the new page. I tried adding a variable named "errorcount" so each function so that the number of errors that occur when the form is submit will be either counted, or removed from the count, and then considered when changing the page...
if(isset($_POST['submit']) ){
if ($errorcount == 0){
header("Location:confirmed.php");}}
This didn't work either. I realized that $errorcount wasn't actually being updated at all; for what reason, I'm not sure. I set it up so each function returns $errorcount, and then called each function in the snippet of code above before running the second if statement, but it still does nothing.
I feel like I'm approaching this the wrong way, but I'm not really sure how else to do this. Please tell me if there's an easier way to achieve this, or maybe you have an idea what I'm doing wrong in the first place.
EDIT:
I am passing the variable $errorcount as global in each function, like so:
function validateName ($name, $submit){
global $errorcount;
if( empty( $submit )) {
return '';}
if (empty ($name)){
return "You didn't enter your name!";
$errorcount = $errorcount+1;
}
if (!preg_match("/^[a-zA-Z \-]*$/",$name, $matches)){
return "Please enter a valid name";
$errorcount = $errorcount+1;
}
else{
$errorcount = $errorcount-1;
}
return $errorcount;
}
However, $errorcount still does not actually change with the if loop I posted above. If I take that out (the section of code that causes the page to change) then the functions work as intended; once you click submit, the page refreshes, and error messages appear where the user did not fill out the form properly. But once all the form areas are filled out properly, clicking submit does... nothing.
EDIT 2:
I got it working. It's honestly not very efficient but it does what I need it to do. Thanks to all who helped!
You don't really need to count the errors, and you don't need to use global. Just write your validator functions so they return an error message if there is an error, or nothing if there is no error. Like this, for example:
function validateName($name) {
if (!$name) {
return 'name is required';
}
if (!preg_match("/^[a-zA-Z \-]*$/", $name)) {
return "Please enter a valid name";
}
}
Then when you run your validators, add any error messages you get to an array.
if ($error = validateName($_POST['name'] ?? '')) {
$errors['name'] = $error;
}
After you run all the validators, if the error array is empty, then there were no errors so you can redirect. And if it's not empty, then you have an array of errors keyed by field name, so you can display any errors next to the problematic fields, which your users will prefer rather than getting one error at a time in some generic location.
if (empty($errors)) {
// redirect
} else {
// stay here and show the errors
}
You're needlessly complicating things. Defining functions are only useful if you plan on re-using that code elsewhere. Try this instead:
if ( isset($_POST['submit']) )
{
if ( empty($name) )
{
echo "You didn't enter a name!";
sleep 3;
// redirect or re-load the form
}
elseif ( !preg_match("/^[a-zA-Z \-]*$/", $name, $matches) )
{
echo "Enter a valid name!";
sleep 3;
// redirect or re-load the form
}
header("Location:confirmed.php");
}
I have created a page on which a form posts its value. So I add some lines to get those values like
$parameter = mysqli_real_escape_string($con,$_POST['Parameter']);
But when I open that page without that form it shows Notice that
Undefined index parameter in page on line.
So I want to make something like if I post the values then only specific area will work.
Otherwise remaining area will work just like if condition.
For ex.
if(post)
{}
else
{}
How can I do this?
First you would need to check if the values are set properly..You can do it with the if condition which would be like
if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST)){
// do the things after form processing
}else{
//things you want to do after form breaks.
}
Use isset() to check
if(isset($_POST['Parameter'])){
//desired tasks
//$parameter = mysqli_real_escape_string($con,$_POST['Parameter']);
}else{
//other task
}
You can use isset() function. In your case if should be like
if(isset($_POST['param']))
{
//Do something
}
else
{
//Do something else
}
I'm developing a plugin for wordpress, the parameter of the $ _GET is recorded in the database according to the preference of the User via the Wordpress Admin Panel. The following validation has to be via the $ _GET, this is the function:
$db_url = get_option('my_get_url');
// returns the value of the database entered by User
// on this case return --> page=nosupport
$url_explode = explode("=", $db_url);
$url_before = $url_explode[0]; // --> page
$url_after = $url_explode[1]; // --> nosupport
echo "Before: ".$url_before; // here are ok, return --> page
echo "After: ".$url_after; // here are ok, return --> nosupport
My problem is here:
// here $_GET no have any value, dont work on validate...
if($_GET[$url_before] != ""){
if($_GET['$url_before']=="nosupport"){
// my function goes here...
}
}
I using for test the parameter:
echo $_GET[$url_before];
But dont return any value...
I found the problem, i had already tested all of these options, but ever dont working, the problem was that I was testing the function inside the main page of my site, and on the main page (mysite.com) does not get the parameter (?page=nossuport), so always returning null values, when I used the variable in the GET or used the echo $GET[$my_var] to test.. It was a great carelessness of mine, would never work...
by the way, the two parameters works correctly:
$_GET[$url_before]
$_GET["$url_before"]
The Problem are solved, Thanks for help.
if($_GET[$url_before] != ""){
if($_GET[$url_before]=="nosupport"){ // note no "" here
// my function goes here...
}
}
In your solution, the key was treated as a string, with no variables evaluated.
You forgot to take out the ' in the second condition.
You wrote:
$_GET['$url_before']
I'm guessing it should be:
$_GET[$url_before]
foreach($_GET as $key => $value){
if($key == "nosupport"){
}
}
I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!
I have a PHP page with a list of items pulled from a database. Each item has an input form next to it, and right at the bottom, a submit button.
How can i do a POST check to find out which inputs have had data added? I can get the data, but how do I know the names of the particular inputs that have been filled?
Iterate over $_POST and list the keys which have nonempty values.
foreach ($_POST as $key => $value) {
if (!empty($value)) {
echo $key . " was filled in.";
}
}
Take a look at the isset() function of PHP - http://php.net/manual/en/function.isset.php.
For Example,
<?php
if(isset($_POST['somevar'])) {
// if the value has been set, this code is executed
} else {
//value not set, so execute this code.
}
?>