Geting error while using $_POST to insert data to database - php

I am trying to make a webapp using php. In that app i need to create Batch, Batch Subject etc. I have complited major part of this app. Althou it is working but i am geting an error notice like:
Notice: Undefined index: currentBatchId in C:\wamp64\www\sp\addBatchSubject.php on line 4
I have passed a batch Id from "batchview.php" page to add a batch subject using this code:
Add Subject
By using the below code:
$currentBatchId=$_GET['currentBatchId'];
I can receive that value and can show in this page with out any problem. But while i want to add some data to the database using this code:
if(isset($_POST['add']))
While i press [add} button it generate the error Notice, but data inserted to the database successfully. Now i want to remove the error.
What is the wrong? while data insert code is posting the data to the database, Is the $_GET try to get another value ?
NB: $_GET & $_POST are in the same page.

If I'm following you right I think you need to switch the order of your code around..
<?php
if(isset($_POST['add'])) {
// handle adding new
// make sure to header("Location: xxx.php"); to remove post data
exit(); // because we don't need to continue
}
if(isset($_GET['currentBatchId'])) {
$currentBatchId=$_GET['currentBatchId'];
}
// then maybe you also need to handle the no post / get request
if(!isset($_POST['add']) && !isset($_GET['currentBatchId'])) {
// handle this case
// maybe header("Location: blah.php");
// maybe exit(); here too because we don't have enough information to render the page
}
Hope that makes sense

Related

Different profile page for different users using PHP

Hey I'm new to php need help creating anew page per user. I have a user login and registration system already. I also have a profiles.php page but, how can I let the website make an automatic webpage for every new user.
Whenever I try to connect it through $_GET or $_POST I get an Undefined index error.
include ("includes/profiles.dbh.inc.php");
$requested_user = $_POST['mailuid'];
try{
$stmt2 = $conn2->prepare("SELECT * FROM profile WHERE id = ?");
$stmt2->execute(array($requested_user));
$mydata = $stmt2->fetch();
} catch (Exception $e) {
//error with mysql
die();
}
I've seen this question come up a few times. One of the first things you need to consider is how is the user going to interact with this page.
Are they going to access it via links? http://example.com/index.php?user=1
Or are they going to submit a form via post? http://example.com/index.php
This distinction is important because it changes the way you handle their request.
Let's look at each one:
Via a link: http://example.com/index.php?user=1
This will issue a get request to your server so you need to handle it via $_GET.
if (isset($_GET['user'])) {
$userId = $_GET['user'];
// ... query your DB and output result
}
Via a form using post: http://example.com/index.php (body with contain "user=1").
This will issue a post request to your server so you need to handle it via $_POST
if (isset($_POST['user'])) {
$userId = $_POST['user'];
// ... query your DB and output result
}
On a side note, it is important to know that an HTML <form> can submit either a post or get request. You can control this via it's method attribute. If you don't specify the method attribute, then it defaults to get.
<form method="post">
...
</form>
<form method="get">
...
</form>
So, to answer your question. You're likely getting an undefined error because you're trying to access the post array using the key mailuid ($_POST['mailuid']) but that does not exist. It doesn't exist because:
you're receiving a get request and the post is empty OR
you are receiving a post request but it doesn't contain the key mailuid
To debug, go back to the basics - use $_GET
Change your code to use $_GET['mailuid'] and then make sure you access your page with the corresponding query string - ...?mailuid=1.
Finally, turn on error reporting - https://stackoverflow.com/a/5438125/296555. You should always do this and correct all errors and warnings.

Display Php Code in HTML

Check the following code. I want to display the send mail parameters like mail, subject and message in HTML page. Please let me know how can i display it in HTML
// send email notification
if (($ed['notify_email'] == 'true') && ($ed['notify_email_address'] != ''))
{
$email = $ed['notify_email_address'];
$template = event_notify_template('email',$ed,$ud,$od,$loc);
sendEmail($email, $template['subject'], $template['message'], true);
}
You can use PHP's echo or print methods to display variables.
<?php echo($myVariable); ?>
or
<?php print($myVariable); ?>
If you want to perform your sendmail action in one php page, then redirect to another and show the data, then you need some means of storing it between views.
if your sendmail is successful store a record of it in your database, and pass the key for that record to your next php page. In that one, query the data for that key, get the result and display it using echo or print.
Similar to above, but store the data in the user's session (not really advised), and display it on the next page using echo or print.
Don't store the data, but pass it along to your next page as GET key/value pairs (not really recommended either), access it in the $_GET[] array and display it using echo or print.
The best solution in your situation is option 1. Store the record, look it up when you need it and display it. It's more secure and you're not putting the user's data in session or passing along in the query string. Plus it gives you a historical record in your database of actions in your site.

post-redirect-GET, GET? How?

Since I asked my question (Previous question) in a way no doubt most users think "dude this is tl;dr" let me put it more simple. I want to use post-redirect-get pattern to avoid user refreshing the site and resubmiting the data etc... I understand that in order to do so I have to redirect the user from html form, through php processing script and back to a new site (or original html form site) that displays the processed data.
Now my question. How do I GET my processed data back from my php? I don't understand the GET part... Currently I don't know how to show php generated data in a nice html display (view) page without include 'site.html';. This example isn't what I am looking for either: Simple Post-Redirect-Get code example. Code in the below example just redirects me to a current page.
It depends on context, but for example:
Given: invoice-form.html, invoice-processing.php and current-invoices.php:
User fills in data on invoice-form
User submits form which has action="invoice-processing.php"
Browser POSTs data to invoice-processing
invoice-processing takes the data from the form and puts it in a database
invoice-processing outputs 302 status and a Location header
Browser goes to current-invoices
current-invoices fetches a list of invoices (including the most recently submitted one) from the database and sends them to the browser as an HTML document
I hope this will help because it has taken me quite a while to get it as well. I tested my understanding like this. I have two php pages, the first page (prg1.php) sends the form to the database, action set to the second one (prg2.php). prg2.php checks the POST data, updates the database and issues a redirect to prg1.php with anything I need to pass back as GET variables. prg2.php looks like this
<?php
if (isset($_POST['gameid'])){
// process the data, update the database
$gameid = htmlspecialchars($_POST['gameid']);
$playerid = htmlspecialchars($_POST['playerid']);
$message = htmlspecialchars($_POST['message']);
//redirect, after updating the database
$getinfo = '?gameid=' . $gameid . '&playerid=' . $playerid;
header("Location: prg1.php" . $getinfo );
exit();
}
?>
You could try something like this:
/****************************************/
/* Fetch my data. */
/****************************************/
$mydata = $_GET["data"];
/****************************************/
/* Has to be sent before anything else! */
/****************************************/
header( 'Location: http://www.yoursite.com/index.php?data='.$mydata );

Php header('Location") error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I'm having some difficulty with my php coding.
I have 3 files, add.php, lib.php, and view.php
I created a simple form, and when the user clicks submit, it should direct them to the view.php where it will display the database. Now I'm having a couple issues I can't seem to resolve.
when the user clicks submit and the fields are blank or there is an error no entry should be made into the view page (or database)...however when I click submit a blank entry is made into the database. ALSO if i click "enter product" from the top menu bar anytime I click it, it causes a blank entry into the database. I can't figure out why that's happening.
My next issue is with the header('Location')
and my browser says:
"Warning: Cannot modify header information - headers already sent by (output started at lib.php:13) in add.php on line 16"
However if I click submit on my form it goes away.
Here is the code for the pages:
I truly apologize if the code is really messy.
Any help / advice / solution is greatly appreciated thank you.
And yes this was an assignment---it was due last week but since I couldn't finish it, it's not worth any marks anymore.
Your if statement if (empty($_POST)){ will always fail and the else will run, thus the empty db entries.
$_POST will always have something in it, even for empty text inputs. Each key will be set to an empty string.
To test for whether you should save data or not you'll need to validate all required form fields. Your code will probably look something like this. This is by no means complete or secure, but it'll point you in the right direction.
<?php
// store validation rules for required fields
$requiredFields = array(...);
// Store all validation errors here.
$errors = array();
foreach($requiredFields as $key=>$rule) {
if(empty($_POST[$key])) {
$errors[$key] = true;
}
else {
// you can perform more validation work on the value here.
}
}
if(count($errors) > 0) {
// form submit failure.
}
else {
// form submit success, save to db
}
You are sending output before setting the header, thus the specified headers are not sent.

HttpWebRequest POST and retrieve data from php script after login

Hello guys i am newbie to this stuff so i'll try to explain my problem.I am building application that retrieve data after login to php script that looks like this:
https://zamger.etf.unsa.ba/getrssid.php
(see the page source for php scirpt definition)
and definition(source) here:
Korisničko ime (UID):
Šifra:
After i login it shows me data that i must collect like this:
RSSID: 1321B312 (this is only data that it shows and nothing else)
I must do this with httpwebrequest but don't know how i tried to do it with POST(data) but it always give me the defnition of php script as response.But i need response to be like "RSSID: 1321B312" not as script definition mentioned above...please heeelp ASAP....
Define a form action to begin. So if the same page, getrssid.php, will be processing the form, use:
<form action="getrssid.php" method="POST">
After that, you must code getrssid.php to accept the incoming data via POST. POST data is stored in the PHP variables $_POST['inputname']. So if you have the input name as "login", the value entered will be stored in $_POST['login']. Same thing applies for the password.
So, here's a sample of what a basic POST data handling script should look like. Note that this script does not verify the login credentials, sanitize the inputs, or anything of the sort. It is just to show you how to handle POST DATA.
<?php
if (isset($_POST['login']) && isset($_POST['pass'])){
// Form is submitted.
echo 'RSSID: 1321B312';
} else {
// Form is not submitted.
// Display Form.
echo 'Form HTML here';
}
?>
If you are really server conscious, you should put the if ... else statement in the opposite order so the most likely outcome (form not submitted) is evaluated first.
Merry Christmas!

Categories