Get variable from query string - php

I was trying to get variable in Query String from URL. But somehow, its just got one variable instead of getting all variables from querystring. I really don't know what goes wrong with my code. Here is the code I want to print out error from the invalidate form:
<?php
displayForm();
function displayForm(){
?>
<form action="./prod_add_action.php" method="post" name="addproductForm">
<fieldset>
<legend>Online Ordering System Setup</legend>
<label for="product_name">Product Name: </label><input type="text" name="product_name" value="" /><?php echo $_GET["name_error"]; ?>
<label for="product_date">Product Date: </label><input type="text" name="product_date" value="" /><?php echo $_GET["date_error"]; ?>
<label for="product_price">Product Price: </label><input type="text" name="product_price" value="" /><?php echo $_GET["price_error"]; ?>
<input name="add_button" type="submit" value="Add" />
<input name="reset_button" type="reset" value="Clear" />
</fieldset>
</form>
<?php
}
?>
And here is the code I created the querystring:
$query_string = "name_error=" .urlencode($name_error) ."&date_error=" .urlencode($date_error) ."&price_error=" .urlencode($price_error);
header("Location: ./prod_add.php?$query_string");
exit();
In the first code, the page only print the first $_GET['name_error'], while it should be include $_GET['date_error'] and $_GET['price_error. ']
This is the address:
http://example.com/prod_add.php?name_error=Product+name+must+be+characters+only&date_error=Product+date+must+be+input+as+this+formate+DD-MM-YYYY&price_error=Product+price+must+be+float+number+only

You should use & instead of &'s ?
$query_string = "name_error=" .urlencode($name_error) ."&date_error=" .urlencode($date_error) ."&price_error=" .urlencode($price_error);
header("Location: ./prod_add.php?$query_string");
exit();

Change & to & as:
$query_string = "name_error=" . urlencode($name_error) . "&date_error=" . urlencode($date_error) . "&price_error=" . urlencode($price_error);
header("Location: ./prod_add.php?$query_string");
exit();

Related

Passing PHP variable data onto another page after validation

While I found something similar to this question on here it didn't answer my question outright.
I have set up this php script to validate the form data, which works, after its validated I want it to then pass the info onto another script page to let the user then verify their input data and then mail the data. Its at this state that I'm having trouble. I've spent the last few days trying to find a solution to this and unfortunately coming up short.
<?php
$name_error = '';
$email_error = '';
$comments_error = '';
$error = false;
if (!empty($_POST['submitted']))
{ //if submitted, the validate.
$name = trim($_POST['name']);
if (empty($name))
{
$name_error='Name is required';
$error = true;
}
$email = trim($_POST['email']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$email_error='E-mail address not valid';
$error = true;
}
$comments = trim($_POST['comments']);
if (empty($comments))
{
$comments_error='Comments are required';
$error = true;
}
if ($error == false)
{
$name_send = $name;
$email_send = $email;
$comments_send = $comments;
/* Redirect visitor to the thank you page */
header('Location: /mail.php');
exit();
}
}
The form this is attached to:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<label>Your Name</label><br />
<input type="text" name="name" style="width:95%" class="text" value='<?php echo htmlentities($name) ?>' />
<br/>
<span class='error'><?php echo $name_error ?></span>
<br />
<label>Email</label><br />
<input type="email" name="email" style="width:95%" class="text" value='<?php echo htmlentities($email) ?>' />
<br/>
<span class='error'><?php echo $email_error ?></span>
<br />
<label for="comments" style="font-size:16px;">Feedback Comments</label><br />
<textarea name="comments" style="width:95%;" rows="8" value='<?php echo htmlentities($comments) ?>'></textarea>
<br />
<span class='error'><?php echo $comments_error ?></span>
<br />
<input type="checkbox" name="allowCommentPublish" checked="checked" />
<label for="allowCommentPublish" style="font-size:10px;">Allow these comments to be used on our website</label>
<fieldset class="optional">
<h2>[ OPTIONAL ]</h2>
<label>Company Name</label><br />
<input type="text" name="companyName" style="width:95%" class="text" />
<br/>
<label>Phone</label><br />
<input type="text" name="phone" style="width:95%" class="text" /><br/>
<div style="margin:5px 0px;">
<input type="checkbox" name="incmarketing" />
<label style="font-size:10px;"> Yes, you can email me specials and promotions.</label>
<br/>
</div>
</fieldset>
<fieldset>
<input type="submit" name="submitted" value="Send" />
</fieldset>
I will point out im focusing on the main data inputs: Name E-mail and comments.
I need the info from this form to be sent onward but i dont know exactly how to do this and any help will be appreciated greatly.
For passing the values to next page you will have to use either of the three methods.
1. Set cookies with the data.
2. Use global variable session.
3.Pass the data in the url.
For cookies u can set cookies with the values like
setcookie('name',$name);
in ur next page read those cookie data
For sessions:
$_SESSION['name']= $name;
for reading data from cookies & session:
$name = $_COOKIE['name'];
$name = $_SESSION['name'];
For using sessions you must add the line
session_start();
at the start of both the pages that send or receive(use) the data
and for urls
header('Location: /mail.php?name=$name&email=$email&comment=$comments');
Read more on using session
If you need to pass values from one script to another you can use $_SESSION variables. To start a session use: (at the top of the php script)
session_start();
$_SESSION['somename'] = $somevariable;
To access or get that same variable you can use this:
session_start();
$some_other_variable = $_SESSION['somename'];
or you can use hidden input fields.
You can use hidden fields and javascript to submit the form. However as this is the same php page as the original form you will need an if statement
echo '<form name="newForm" action="newpage.php" method="POST">';
echo '<input type="hidden" name="name2" value"' . $name . '">;
echo '<input type="hidden" name="email2" value"' . $email . '">;
echo '<input type="hidden" name="comments2" value"' . $comments . '"></form>;
echo '<script> if (document.getElementById("name2").value != ""){window.onload = function(){ window.document.newForm.submit(); }} </script>';

Checks In PHP are not working

I am working in PHP. i have made a form named as Donor.php and a connect it to database. Now I am trying to apply checks in on it in PHP. But their is a problem. As I have applied checks for empty fields in PHP on a form but these checks are not working. Please check out my code. As my work is stuck just because of this problem. My code file is here:
Donor.php
<?php
//error_reporting(0);
if(isset($_POST['submit'])){
$first_name=$_POST['firstname'];
$last_name=$_POST['lastname'];
$Country=$_POST['country'];
$City=$_POST['city'];
$Gender=$_POST['gender'];
$Email=$_POST['email'];
$Password=$_POST['pwd'];
include_once "connectionn.php";
$emailChecker=mysql_real_escape_string($Email);
$sql_email_check=mysql_query("Select Email FROM user WHERE Email='$emailChecker'");
$email_check=mysql_num_rows($sql_email_check);
if((empty($first_name)) ||(empty($last_name)) ||(empty($City)) ||(empty($Gender)) ||(empty($Email)) ||(empty($Password))) {
$errorMsg='We are sorry, but there appears to be a problem with the form you submitted.';
if (empty($first_name)) {
$errorMsg.='$var is either 0, empty, or not set at all';
header('Location: Donor.php');
}
if(empty($last_name)){
$errorMsg.='lastname';
header('Location: Donor.php');
}
if(empty($City)){
$errorMsg.='City';
header('Location: Donor.php');
}
if(empty($Gender)){
$errorMsg.='Gender';
header('Location: Donor.php');
}
if(empty($Email)){
$errorMsg.='email';
header('Location: Donor.php');
}
if(empty($Password)){
$errorMsg.='Password';
echo "$errorMsg.";
header('Location: Donor.php');
}
}else if($email_check>0){
$errorMsg="invalid";
}else{
$sql="INSERT INTO user (User_ID,First_Name, Last_Name, gender, city, Email, Password) VALUES (NULL,'$first_name', '$last_name','$Gender','$City','$Email','$Password')";
$result=mysql_query($sql);
$UserID="SELECT max(User_ID) as usr from user";
$userIDResult=mysql_query($UserID);
if($userIDResult === false)
{
die(mysql_error());
}
while($R=mysql_fetch_array($userIDResult)){
$usrID= $R['usr'];
}
$donor="INSERT INTO donor(User_ID, Country)Values('".$usrID."','$Country')";
$resultdonor=mysql_query($donor);
mysql_close();
header('Location: DonorPro.php');
}
}
?>
<?php
include "Header.php";
//include "registration.php";
?>
<div class="DonorDiv">
<h1>Lets Join:</h1>
<form name="input" action="" method="post" <?php print"$errorMsg"; ?>>
First Name: <input type="text" name="firstname" placeholder="First Name" id="r">
<?php print "$first_name";
// if (!isset($_POST['firstname'])) {
//echo '$var is either 0, empty, or not set at all';
//}
?>
Last Name: <input type="text" name="lastname" placeholder="Last Name" id="u" <?php print "$last_name";?>> <br>
Institution: <input type="text" name="country" placeholder="Institution" id="" <?php print "$Institution";?>>
City: <input type="text" name="city" placeholder="City" id="" <?php print "$City";?>><br>
Country: <input type="text" name="country" placeholder="Country" id="" <?php print "$Country";?>><br>
Gender: <input type="text" name="gender" placeholder="Gender" id="" <?php print "$Gender";?>><br>
Email Address: <input type="Email" name="email" placeholder="Email" id="g" <?php print "$Email";?>><br>
Password:<input type="Password" name="pwd" placeholder="Password" id="v" <?php print"$Password";?>><br>
<input type="submit" src="images/button(9).png" alt="Submit" id="q">
</form>
</div>
<?php include "Footer.php"; ?>
The PHP mysql lib is deprecated, you should consider using myslqi or php PDO instead.
Here is a tutorial
You should also be careful : $first_name and the other variables as they are not defined when you display the form, so you will get warnings.
Anyway, your problem is that this check is always false :
if(isset($_POST['submit'])){
The easiest (but not the best) way to correct that is to add a hidden input in your form :
<input type="hidden" name="hidden">
You have to quit the PHP script after telling the browser to redirect to another page:
header('Location: Donor.php');
exit;
(Besides SQL injection and some other problems.)

Class variables NULL?

I am working on a web back-end that will pull information into a form, and then when updated, will update the database with the new information. However, when I try to pull information previously stored in a class private variable, it throws me an error stating that the information is NULL. What am I doing wrong here?
<?php
class modify_racer
{
private $mysqli, $racer_id, $firstname,
$lastname, $banner, $bio;
public function error($code)
{
switch($code)
{
case 1:
echo '<p id="error"><b>Error:</b> Please fill out all fields!</p>';
modify_racer::send_form($this->firstname, $this->lastname, $this->banner, $this->bio);
break;
case 2:
echo '<p id="error"><b>Error:</b> Racer already exists!</p>';
break;
case 3:
echo '<p id="error"><b>Error:</b> Could not connect to MySQLi: ' . mysqli_error();
break;
}
}
public function send_form($modify = 1)
{
?>
<div id="form">
<h3>Edit Racer:</h3>
<form method="post" action="">
<label for="firstname">First Name: </label>
<input type="text" id="firstname" name="firstname"
placeholder="Racer's First Name"
value="<?php echo $this->firstname;?>" />
<br />
<label for="lastname">Last Name: </label>
<input type="text" id="lastname" name="lastname"
placeholder="Racer's Last Name"
value="<?php echo $this->lastname;?>" />
<br />
<label for="banner">Banner Location: </label>
<input type="text" id="banner" name="banner"
placeholder="Racer's Banner Image Location:"
value="<?php echo $this->banner;?>" />
<br />
<label for="bio">Racer's Bio Info: </label>
<textarea rows="5" cols="50" id="bio" name="bio"
placeholder="Racer Statistics / Biography"
value=""><?php echo $this->bio;?></textarea>
<input type="submit" id="submit" name="modify" value="submit" />
</form>
</div>
<?php
}
public function get_racer($racerID)
{
$this->racer_id = $racerID;
$this->mysqli = new mysqli(MYSQLI_HOST,MYSQLI_USER,MYSQLI_PASS,MYSQLI_DATABASE)
or die(error(3));
$racer_info = "SELECT * FROM ArtecRacers WHERE RacerID=?";
$load_racer = $this->mysqli->prepare($racer_info);
$load_racer->bind_param('s', $racerID);
$load_racer->execute();
$load_racer->bind_result($this->racerID, $this->firstname, $this->lastname, $this->banner, $this->bio);
$load_racer->fetch();
modify_racer::send_form();
}
public function list_racers()
{
?>
<div id="form">
<h3>Select Racer:</h3>
<form method="post" action="">
<?php
$this->mysqli = new mysqli(MYSQLI_HOST,MYSQLI_USER,MYSQLI_PASS,MYSQLI_DATABASE)
or die(error(3));
$racer_list = "SELECT * FROM ArtecRacers";
$get_racers = $this->mysqli->query($racer_list);
while($list = $get_racers->fetch_array(MYSQLI_NUM))
{
echo '<input id="part" type="radio" name="editRacer" value="' . $list[0] . '"/>';
echo '<label for="part">' . $list[1] . ' ' . $list[2] . '</label><br />';
}
?>
<input type="submit" name="selectRacer" id="submit" value="Select Racer" />
</form>
</div>
<?php
}
function test2()
{
echo $this->firstname;
echo $this->lastname;
echo $this->racer_id;
}
}
$start = new modify_racer();
if(!isset($_POST['selectRacer']))
$start->list_racers();
if(isset($_POST['selectRacer']))
$start->get_racer($_POST['editRacer']);
$start->test2();
?>
Everything in the code works except at $start->test2(); all of the information pulled from the function test2() is blank, and I am not sure why... Any insights?
EDIT:
I changed the code to reflect the following on the bottom, and test2() still outputs the variables as NULL:
if(!isset($_POST['editRacer']))
$start->list_racers();
else
$start->get_racers($_POST['editRacer']);
$start->test2();
If you leave your code alone, you're going to have to pass both selectRacer and editRacer parameters into the page. My guess is that you might only want to pass the one, though. In which case, you'll want to change
if(isset($_POST['selectRacer']))
$start->get_racer($_POST['editRacer']);
into
if(isset($_POST['editRacer']))
$start->get_racer($_POST['editRacer']);
Also, if you want to pass these values in through the URL bar, you need to check $_GET, not $_POST.
And finally, everywhere that you are making method calls by executing modify_racer::my_method_here(), you should change that to $this->my_method_here(). The former is a static method call, meaning it's not actually associated with your object, meaning it can't touch those variables. For it to be able to access and change the variables, you'll need to call it through $this.

Echo in a form when user did not insert all info needed

This is a part of my registration form. I want to display back the input user inserted if they forgot to enter all the info needed. However, I get this on my textbox in register form where everyone including my user can see it.
Notice:Undefined variable: name in D:\XAMPP\htdocs\registration.php on line 113
I want it to echo back the input that user had inserted and display it again so that user does not have to enter the same input over again. Help ?
$myusername=($_POST['username']);
$name=($_POST['name']);
if(isset($_POST['username'])) {
echo $_POST['username'];
}
if(isset($_POST['name'])) {
echo $_POST['name'];
}
<input type="text" name="username" size="60" value="<?php echo $myusername; ?>"/>
<input type="text" name="name" size="60" value="<?php echo $name; ?>"/>
Assuming you send the user back to the page they were at previously if the form fails to validate, the POST array is emptied. POST will only carry the information to the page that the form is submitting to.
You can use sessions to save the data in an array, indexed by form field name. Then when the user is sent back to the form, if there are any entries in the array, you can iterate over them through to your form fields.
you can controll the variables with if clause; means you can write:
if ( isset($_POST['send']) && isset($myusername) ) {
echo $myusername;
}
else {
echo '<span style="color:red;">Please complete this field</span>';
}
and do the same in html value for textfiels...
$myusername = isset($_POST['username']) ? ($_POST['username']) : '';
$name = isset($_POST['name']) ? ($_POST['name']) : '';
<input type="text" name="username" size="60" value="<?php echo $myusername; ?>"/>
<input type="text" name="name" size="60" value="<?php echo $name; ?>"/>
Try this, this should remove your error?
if(isset($_POST['username'])) {
$myusername=($_POST['username']);
<input type="text" name="username" size="60" value="<?php echo $myusername; ?>"/>
echo $_POST['username'];
}
if(isset($_POST['name'])) {
$name=($_POST['name']);
<input type="text" name="name" size="60" value="<?php echo $name; ?>"/>
echo $_POST['name'];
}
Here we are checking for POST value first then we using it.
Write the isset function inside the value of each of your .
Exemple :
<input type="text" name="username" size="60" value="
<?php if( isset( $_POST["myusername"] ) )
echo $_POST["myusername"] ?> "/>
you can use this tutorial for validation of input fields in php
http://www.w3schools.com/php/php_form_validation.asp
or you can use this method
<?php
$myusername="";
$name="";
if(isset($_POST['submit'])){
$myusername = $_POST['username'];
$name = $_POST['name'];
}
?>
<form method="POST" action="">
<input type="text" name="username" size="60" value="<?php echo $myusername; ?>"/>
<input type="text" name="name" size="60" value="<?php echo $name; ?>"/>
<input type="submit" name="submit" size="60" value="submit"/>
</form>

Define php var after textbox

So I have a variable well defined in a php page and I'm using it in an HTML page using include.
I am currently building a page where I can change the Var ( because it's a long text, more than one actually, and to change them it will be nice to have a page with a layout just for that) so I'm using a textbox and a submit button just like this:
<?php
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
?>
<form method="post">
Titre: <input name="titre" type="text" id="titre" value="<?php echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit']))
{
$titre = $_POST['titre'];
echo($titre);
}
?>
The problem is that in the echo it shows the new text but if I do a refresh it will show the old one...
any ideas how can I do this?
EDIT: Added extra fields and data handler. See extra code below original answer.
Here is some code I came up with to write content to a file.
Note: To add to the file with content written one under the other, use the a or a+ switch.
To create and write content to file and overwrite previous content, use the w switch.
This method uses the fwrite() function.
(tested)
Added to OP's code: action="write.php"
FORM
<?php
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
?>
<form method="post" action="write.php">
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
PHP write to file handler (write.php)
This example uses the w switch.
<?php
if (isset($_POST['submit']))
{
$titre = $_POST['titre'];
echo($titre);
}
?>
<?php
$filename = "output.txt"; #Must CHMOD to 666 or 644
$text = $_POST['titre']; # Form must use POST. if it uses GET, use the line below:
// $text = $_GET['titre']; #POST is the preferred method
$fp = fopen ($filename, "w" ); # w = write to the file only, create file if it does not exist, discard existing contents
if ($fp) {
fwrite ($fp, $text. "\n");
fclose ($fp);
echo ("File written");
}
else {
echo ("File was not written");
}
?>
EDIT: Added extra fields and data handler.
Extra fields can be added, and must be followed in the same fashion in the file handler.
NEW FORM with extra fields
File data example: test | email#example.com | 123-456-7890
<?php
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
?>
<form method="post" action="write.php">
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<br>
Email: <input name="email" size="50" maxlength="50">
<br>
Telephone: <input name="telephone" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit']))
{
$titre = $_POST['titre'];
echo($titre);
}
?>
PHP write to file handler
<?php
$titre = $_POST['titre'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$data = "$titre | $email | $telephone";
$fp = fopen("data.txt", "a"); // a-add append or w-write overwrite
if ($fp) {
fwrite ($fp, $data. "\n");
fclose ($fp);
echo ("File written successfully.");
}
else{
echo "FAILED";
}
?>
<?php
if(!($titre = file_get_contents("filename.txt"))){
$titre= 'Bienvenido a PARIS EXPERT LIMOUSINE ! ' ;
}
?>
<form method="post">
Titre: <input name="titre" type="text" id="titre" value="<?php echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$titre = $_POST['titre'];
if(#file_put_contents("filename.txt", $titre))){
echo 'Success - var stored.';
} else { echo 'Some error.'; }
echo($titre);
}
?>
Try this :
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
If you need to keep your value for ever, you should store it in a database or save it in a file (could be .txt).
[EDIT]
Here is the code for .txt solution (you first create a file.txt in the same folder):
<?php
$file = 'file.txt';
$lines = file("file.txt");
if (!isset($lines[0])) {$titre='Bienvenido a PARIS EXPERT LIMOUSINE ! ';}
else {$titre=$lines[0];}
?>
<form method="post">
Titre: <input name="titre" type="text" id="titre" value="<?php if(isset($_POST['titre'])){echo htmlspecialchars($_POST['titre']); }
else echo htmlspecialchars($titre); ?>" size="50" maxlength="50">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit']))
{
echo($_POST['titre']);
$titre = $_POST['titre']."\n".$titre;
file_put_contents($file, $titre);
}
?>
Hope it helps :)
this is normal because you're showing the new content upon form submission. When you refresh the page, unless you tell it to send the POST data again with the refresh (which the browser asks you for confirmation), your form (and hence the input field) will have nothing in.

Categories