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.
Related
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
I am trying some code to get value from URL through post method and search database table for that value and get info from the database and encode it into JSON response.
Here is my code :
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","json") or die("Error " . mysqli_error($connection));
if (isset($_POST['empid'])) {
$k = $_POST['empid'];
//fetch table rows from mysql db
$sql = "select `salary` from tbl_employee where `employee_id` = $k ";
} else {
//fetch table rows from mysql db
$sql = "select `salary` from tbl_employee";
}
//fetch table rows from mysql db
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
I used Postman extension on Chrome and pass the values but it is not returning. Instead it is returning the else part.
Postman Screenshot
Looking at your screen shot, you have not passed body key values, instead you passed params.
Click on Body Tab and then pass key & value pair.
As per your screenshot you are sending your empid through query parameter so you need to access that as follows
<?php
if (isset($_GET['empid'])) {
echo $_GET['empid'];
}else{
// else part
}
also for that you need to Request Url in Postman using GET method.
But as you have stated that you want to send empid through POST in postman, you have to send it through form-data in Postman and access it as $_POST["empid"];. following is the screenshot for your reference
else there is another option where you can send the POST data through body as row json and access it as
$rawPostData = file_get_contents('php://input');
$jsonData = json_decode($rawPostData);
and $post will contain the raw data. And you can send it through postman as in following screenshot.
You have to set the Body to "x-www-form-urlencoded" and adding the variables to be posted
Or try this SO question, its already been answered
I replicated the code and db on my system to figure out the problem. I also added some lines of code before if (isset($_POST['empid'])) { for diagnostics sake:
$method = $_SERVER['REQUEST_METHOD'];
echo $method."<br/>";
The application file is index.php deployed in json directory inside webroot.
When I send any request to http://localhost/json directory (either POST/GET), Apache redirects the request as a GET request to index.php (as configured in my Apache config file). I assume this is what you're experiencing.
But when I send the request to http://localhost/json/index.php, the request is accurately received and processed.
Therefore, I would say the solution is that you need to specify the php file and also set the empid parameter as part of the body in Postman (not as part of the url).
I think you should also check the post if emptyif (isset($_POST['empid']) AND ($_POST['empid']) != ""). to allow php to execute the line before else.Sometimes programming becomes unpredictable.
use if(isset($_REQUEST['empid'])) to test in POSTMAN...
Then use if(isset($_POST['empid'])) to test directly from app...
have a look Issue in POSTMAN https://github.com/postmanlabs/postman-app-support/issues/391
To get the value of a variable from the URL(query string), you need to use either $_GET or $_REQUEST.$_POST represents data that is sent to the script via the HTTP POST method.
So, in your code you just need to do this :
$_REQUEST['empid'] instead of $_POST['empid']
In POST method the data is sent to the server as a package in a separate communication with the processing script. Data sent through POST method will not visible in the URL.
Confirm that in postman Content-Type should be application/x-www-form-urlencoded in request header.
Postman reference doc : https://www.getpostman.com/docs/requests
Hey it sounds like you are just needing to do a GET request to your DB.
You are more than welcome to send in variables via a GET request as well.
GET http://localhost/json?empid=3
You can then get data from your GET request like so $_GET['empid']
I suggest a GET request because I see your not actually posting any data to your server, your just handing in a variable in which you want to use to query with.
I do understand that GET requests are less secure, but in your scenario your POST just doesn't seem to want to work. So a different tack might do you justice.
If you want a value from the URL, you need to use $_GET["empid"] instead $_POST["empid"]
Submitting a form through POST method
By post method of form submission, we can send number or length of data. Sensitive information like password does not get exposed in URL by POST method, so our login forms we should use POST method to submit data. This is how we collect data submitted by POST method in PHP
$id=$_POST['id'];
$password=$_POST['password'];
Collecting data submitted by either GET or POST method
If a page is receiving a data which can come in any one of the method GET or POST then how to collect it ? Here we are not sure how to collect the data. So we will use like this.
$id=$_REQUEST['id'];
$password=$_REQUEST['password'];
Looking at the URL you are requesting, you are sending a GET value within your POST request.
http://localhost/json?empid=3
As you can see here, the url holds the empid variable and so the is send to the server as beeing a GET variable ($_GET)
Use $_GET['empid'] to access this variable, while using $_POST to access the other variables.
You could also use $_REQUEST to access both GET and POST data by the same global.
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 );
Basically i have a form where a studentID is inputted, i then want to check id the inputted studentID is in the database, if it is post the form to the next page. If not then display an error on the page where you input studentID
Don't really know where to start
Cheers
is this what you want?
<form id = "form" action = "./?page=markandfeedback" method = "post">
<br>
Mark for:
<INPUT id="stud" onkeypress="return isNumberKey(event)" type="text" name="stud" value="Enter Student Number">
<input type="submit" value = 'Continue'>
<?
$studID = $_POST['stud'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql);
// echo $_SESSION['module'];
if ($result == NULL) { // nothing found
echo "the student id you entered is not in the database";
}
else {
$_SESSION['student'] = $studID;
Header("Location: http://www.whereever.com/"); // send the browser where you want
exit();
}
?>
EDIT:
I went over the other answers. I assume you check for mysql injection properly. I recommend implementing AJAX AFTER everything works and is secure. The idea behind my solution was to solve the problem as simple as possible. If you want to make something fancy out of it you could:
generate the whole form via php and tell the user in the input field, that the id wasn't found
tell your Javascript to present the information in some fancy way
Use AJAX. Everybody loves forms with AJAX.
You could, as suggested, assume that the user entered a valid id. You would check on the "whereever" page wether the id is actually valid. If it weren't, you would simply send the user back to the form and tell the php to output an error message (maybe via get). This possibility is not usual, I am not sure if it has any advantages.
the mysql_num_rows hint is nice, too, if you don't want any data from the user. I thought you wanted to do something with the data because of the SELECT *.
Make a seperate controller that does the checking of the username.
Use ajax to check if user input is valid or not.
So you'll have something like this:
<input id="stud" onchange="checkStudentId(this)" />
<script>
function checkStudentId(inputElement) {
var id = inputElement.value();
$.ajax({
url: "test.html",
context: {id:id}
}).done(function() {
// Check the return result
});
}
</script>
Here is a reference to jquery ajax
http://api.jquery.com/jQuery.ajax/
You actually have to connect to the server in some fashion to figure out of the student exists. What you'd normally do in this situation is submit the form to the server and do validation server-side. If the student exists, you return the "next" page. If the student doesn't exist, then you return (or redirect to using a Location header) the same form again with an error message.
Another popular method would be to use an AJAX request to check asynchronously (which I see many other people are recommending). I'd only recommend this way if you're actually doing validation right as they've finished entering the student id and are showing an error message in real-time, effectively. In this way, AJAX is a nice-to-have to provide quick user feedback, but not a real solution. Keep in mind that regardless of this, you need to check for and handle this when the form is submitted anyway, or at the least, consider what will happen when the form is submitted with an invalid id.
People can bypass this check (EVERY request from the client side is considered hostile, you can't implicitly trust anything)
Another user may have deleted the student ID between the time the check was done and the form was submitted
There could be an error in your code that causes validation to falsely pass or not to recognize a negative response
Doing AJAX onsubmit makes no sense, because effectively you're doubling the amount of work by making the server handle two separate requests in a row. It's simply the wrong answer to the problem.
The biggest trouble with this implementation is the PHP code can quickly get quite hairy and hard to follow as you have everything mixed together.
This is where you probably start to tip over using PHP like a templating language (mixed php code and html markup) and start getting into using a framework where your views (the HTML) are decoupled from your PHP code (if you're using the very-populate MVC pattern, this code is called your controller -- precisely because it controls how the server responds). This is how any professional developer will work. Kohana, CakePHP, and Zend are all examples of fairly popular MVC frameworks, all of which are used professionally.
You can do this in two different ways
AJAX - make ajax call to your server and check the ID if its exist display the error else go to the next page
PHP - put a hidden input in your form and make the action of the form to the same page and check everything their and keep the values of the input fields is the $_POST['field_name'];
And you can make the action into another page and return back variable or make a session to hold the error message
Try this:
<?
if(isset($_POST['stud'])){
$studID = $_POST['stud'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$host="hostname";//your db host
$user="user";//your db user
$pass="pass";//your db pass
$conn=mysql_connect($host,$user,$pass);
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql,$conn);
if(mysql_num_rows($result)>0){//the id was found in the DB, do whatever here...
echo $_SESSION['module'];
$_SESSION['student'] = $studID;
Header("Location: http://www.whereever.com/");//redirect to wherever
$error=false;
}
else{//id was not found
$error=true;}
}//end of isset
?>
<? if($error===true){?> <div> The id was not found.... </div> <?}?>
<form id = "form" action = "<? echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; ?>" method = "post">
<br>
Mark for:
<INPUT id="stud" onkeypress="return isNumberKey(event)" type="text" name="stud" value="Enter Student Number">
<input type="submit" value = 'Continue'>
So what this does is: When the user hits submit, conects to the DB, and checks if the ID exists...if it does, then it redirects it to wherever.com (see comments) and if it don't an error messege will show up. Be sure to change the db variable values to your own ($host, $user, $pass).
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!