Email value not showing using POST method - php

I have this form in which there is only one field i.e. "Email id", so what I have to do is that when I entered the email id the email id must be split into two parts like user name and domain name and must be displayed in next form.
So my problem is that my 2nd form doesn't display the result, however when I used $_SESSION method in place of $_POST(to take value of email field) it takes the value and also split it but takes only one value as I want to take multiple email ids.
For better understanding please check my code.
<?php
session_start();
?>
<!Doctype html>
<html>
<head>
<title>PHP3</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="jumbotron">
<div class="container">
<form class="form-horizontal" method="post" action="screen3_controller.php">
<div class="form-group">
<label class="control-label col-sm-2" for="email_text">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="email_text" id="email_text">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" name="submit" id="submit_button" class="btn btn-default" value="Submit">
</div>
</div>
</form>
</div>
</div>
<table class="table table-striped table-responsive">
<thead>
<tr>
<th>Email Id</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_SESSION['all_post']) && !empty($_SESSION['all_post']))
{
foreach($_SESSION['all_post'] as $key=>$value)
{
?>
<tr>
<td><?php echo $value['email_text']; ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<th>User Name</th>
<th>Domain Name</th>
</tr>
</thead>
<tbody>
<?php
$str = $_POST['email_text'];
$hello = explode("#", $str);
$_SESSION ['emails'] = $hello;
echo "<tr>";
foreach ($_SESSION ['emails'] as $value)
{
echo "<td>$value</td>";
}
echo "</tr>";
?>
</tbody>
</table>
</div>
</body>
</html>
Controller:
<?php
session_start();
$data = $_POST;
if (isset($data['submit'])) {
$_SESSION['all_post'][] = $data;
}
header('Location:screen3_2.php'); exit();
?>

As I can see,
In your code you are posting your form data to controller, not the second page.
Though you are storing your data to $_SESSION in your controller page, That's how you're able to access data from second page.
Solution :
either access data on second page using $_SESSION, or
POST your first page to directly second page, and access data using $_POST.

When the following code executes, it does NOT send the POST vars with it.
They are lost at that point. However, you have stored the data in the session.
header('Location:screen3_2.php'); exit();
Also note that the following code:
$str = $_POST['email_text'];
$hello = explode("#", $str);
$_SESSION ['emails'] = $hello;
Will store the two parts of exactly one email. You mentioned that you want to store multiple emails and this code will not accomplish that.
It seems to me that what you want to do is to keep going back to the same page and reusing the form while collecting email addresses. Please confirm.
Try this:
Do not use a separate controller file. Take that code and remove the redirect. Put that code at the top of the file. This way you collect
all the email addresses from $_POST.
<?php
// Taken from 'controller'
session_start();
// Only process post if it exists
if ( ! empty($_POST) ) {
$data = $_POST;
if ( isset($data['submit']) ) {
$_SESSION['all_post'][] = $data;
}
}
// No redirect
?>
<?php // put the form here ?>
<form class="form-horizontal" method="post" >
<input type="email" class="form-control" name="email_text" id="email_text">
<input type="submit" name="submit" id="submit_button" class="btn btn-default" value="Submit">
</form>
<?php
// output all the email addresses collected
if(isset($_SESSION['all_post']) && !empty($_SESSION['all_post'])) {
foreach($_SESSION['all_post'] as $key=>$value) {
$parts = explode('#', $value['email_text']);
?>
<tr>
<td><?= $parts[0] ?></td> <?php // before # ?>
<td><?= $parts[1] ?></td> <?php // after # ?>
</tr>
<?php
}
}
?>
</form>

Related

display username based results, when logged in as another user (teacher tracking)

I have the following php page in which I am trying to simulate a simple example of searching for a specific username (stored in the database) and when "submit" is clicked, the results for that user are displayed on the page. At the moment, the code shows the results displayed only for the user that is logged in. How do I adapt it to fit with the code to search and track as another user?
HTML:
<p>Welcome, teachers! Here you can track student progress.</p>
<p>Enter the username of the student you wish to 'view' results for</p>
<form action="/action_page.php">
Username: <input type="text" name="FirstName" value="Mickey"><br>
<input type="submit" value="Submit">
</form>
Php related code that only allows the page to load if the user is logged in:
session_start();
if (!isset($_SESSION['username']) or ($_SESSION['username'] == '')) {
header("Location: login.php");
}
?>
Php code that displays the currently logged in user's quiz results:
<table class="table table-hover" style="text-align:center;">
<thead>
<tr>
<th style="text-align:center;">Quiz</th>
<th style="text-align:center;">Score (%)</th>
<th style="text-align:center;">Certificate</th>
<th style="text-align:center;">Retake</th>
</tr>
</thead>
<tbody>
<?php
$a = new NewQuizScore;
$scores = $a->getScores($_SESSION['username']);
foreach ($scores as $score) {
echo ("<tr>");
echo ("<td>".$score[0]. "</td> ");
echo ("<td>".$score[1]. "</td> ");
echo ('<td>Print Certificate</td>');
echo ("<td>Take it again!</td> ");
echo ("</tr>");
}
?>
</tbody>
</table>
</div>
</div>
To reiterate, as a php newbie, I would like a solution (with code in my existing context provided) for how to use the search button to look up a username, and then provide the information for the SEARCHED FOR username in the page, rather than for the username that is logged in. I've tried various things and cannot come up with the logic.
What I've tried:
Along the lines of:
<form action="/action_page.php">
Username: <input type="text" name="username1" value="username1"><br>
and:
$a = new NewQuizScore;
$scores = $a->getScores($_SESSION['username1']);
I was trying to link what is entered in the text box, to the getScores session, but obviously this doesn't work:
Update based on suggested answer - still doesn't work:
<?php
require 'includes/functions.php';
include_once 'config.php';
include 'includes/newquizscore.php';
session_start();
if (!isset($_SESSION['username']) or ($_SESSION['username'] == '')) {
header("Location: login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="#" method="post">
Username: <input type="text" name="username1" value=""><br>
<input type="submit" value="Submit">
</form>
<?php
$username = (!empty($_POST['username1']))? $_POST['username1'] : $_SESSION['username'];
$a = new NewQuizScore;
# This is assuming this action is what you use to get the user's data
$scores = $a->getScores($username)
?>
</body>
</html>
You need to get the value from the form using the $_POST superglobal. $_POST is less transparent than $_GET, so I would use that for your form:
<!-- ADD METHOD ------------------------------->
<!------------------------------vvvvvvvvvvvvv-->
<form action="/action_page.php" method="post">
Username: <input type="text" name="username1" value=""><br>
<input type="submit" value="Submit">
</form>
When you post the form, you can use the script below. Note, since your form is pointing to /action_page.php, that is where this script should be located:
# Fetch the post value OR the current logged in (depending if form submitted or not)
# This is assuming you are searching by username1 value from form
# (since that is what you have in your form). You can use functions like
# trim() to remove empty spaces before and after submitted value to clean
# the input up a bit
$username = (!empty($_POST['username1']))? $_POST['username1'] : $_SESSION['username'];
$a = new NewQuizScore;
# This is assuming this action is what you use to get the user's data
$scores = $a->getScores($username);

Using forms from a tabbed index page

So I'm new to PHP and I'm having trouble getting some of my forms to function. I think it may be the way my site is set up that's causing me problems.
I have index.php which is set up as such:
<div class="pageContent">
<div id="main" style="width:1000px; margin:0 auto;">
<!-- Create the tabs -->
<div id="tabs" >
<ul>
<li>Overview</li>
<li>Ranked</li>
<li>Arena</li>
<li>Decks</li>
<li>New Game</li>
<li>Admin</li>
</ul>
<div id="tabs-0"></div>
<div id="tabs-1"></div>
<div id="tabs-2"></div>
<div id="tabs-3"></div>
<div id="tabs-4"></div>
<div id="tabs-5"></div>
</div>
<!-- Load the pages into tabs -->
<script>
$("#tabs").tabs();
$("#tabs-0").load("tab0.php");
$("#tabs-1").load("tab1.php");
$("#tabs-2").load("tab2.php");
$("#tabs-3").load("tab3.php");
$("#tabs-4").load("newGame.php");
$("#tabs-5").load("admin.php");
</script>
</div><!-- / main -->
</div><!-- / pageContent -->
This gives me a nice static page and 6 tabs of .php files to do cool stuff on.
There are a couple of forms, log in and such, in index.php which all function fine. But when I create a form on a page in a tab, it will not.
Here's an example from admin.php (#tabs-5)
<?php
if(isset($_POST['delLog'])){
unlink('log.txt');
echo 'Success';
}
if(isset($_POST['delLog'])){
unlink('error_log');
echo 'Success';
}
?>
<html>
<head>
</head>
<body>
<table width="100%" border="1">
<tr>
<td width="40%" valign="top">
</td>
<td width="30%" valign="top">
<h1>error_log</h1>
<form action="" method="post">
<input type="submit" name="delErr" id="delErr" value="Delete" />
</form>
<hr />
<?php
$lines = explode("\n", file_get_contents('error_log'));
foreach ($lines as $line){
echo $line.'<br>';
}
?>
</td>
<td width="3'0%" valign="top">
<h1>log.txt</h1>
<form action="" method="post">
<input type="submit" name="delLog" id="delLog" value="Delete" />
</form>
<hr />
<?php
$lines = explode("\n", file_get_contents('log.txt'));
foreach ($lines as $line){
echo $line.'<br>';
}
?>
</td>
</tr>
</table>
</body>
</html>
This is another, better example. A stripped down test I did yesterday for this question
Problems with $_POST
<?php
define('INCLUDE_CHECK',true);
include 'php/functions.php';
error_reporting(E_ALL);
ini_set('display_errors',1);
logThis('ready!');
if (isset($_POST['submit'])) {
logThis('success');
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="">
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
</html>
Neither of these examples work. When the submit button is pressed the site refreshes but no PHP actions are taking place. There is no error message in error_log. I don't think it's getting the call at all.
Neither of the forms return an output, one adds to the database. The other deletes log files.
Hope I've provided enough details.
What ever you are trying to do is not possible at all. You can not load PHP code to frontend, it can only be processed by the server.
The statement $("#tabs-5").load("admin.php"); is fetching only the html code (processed by the server) not the PHP script
<form action="" method="post"> will post to the current page (ie. whatever is in your address bar).
When you load the pages into index.php using ajax, that means the forms will post to index.php... I'm guessing you are expecting to fetch the form submissions in each individual php-file
So to fix it either you have to also post using ajax (and refresh the tabs with the response), or you need to change the action attribute on the forms to each individual php-file... in which case you lose your tabbed layout when a form is submitted. You can work around that as follows:
In each of the php-files you do something like this (using newGame.php as example):
<?php
if (isset($_POST)) {
//Do your form-handling stuff first
// [...]
// ...and then redirect back to index.php
header("Location: index.php");
die();
} else {
//Print your form
echo '<form action="newGame.php" method="post">';
// [...]
echo '<input type="submit" value="Create game">';
echo '</form>';
}
Note that there should be no <html>, <head>, <body> or other html in the "sub-pages" at all - just the bare content you want inside the tabs...
Now for the ajax-submit method you should also remove all "wrapping html", you should still set a target="[...]" on each form, and you should still do form handling inside each individual file. But you should not do a redirect after form handling, but just output the form again:
<?php
if (isset($_POST)) {
//Do your form-handling stuff first
// [...]
//Maybe print a little message to let the user know something happened
echo 'Form completed at ' . date('H:i:s');
}
//...then print your form no matter what
echo '<form action="newGame.php" method="post">';
// [...]
echo '<input type="submit" value="Create game">';
echo '</form>';
Then add this script to index.php - it will post all forms inside the tabs using ajax instead of refreshing the page:
<script>
my_cool_ajax_post = function(form_elm, tab_elm) {
//Actual ajax post
$.post(form_elm.target, $(form_elm).serialize(), function(data){
//Results are in, replace tab content
tab_elm.html(data);
});
};
$(document).on("submit", "#tabs form", function(){
//Store the form element
var form_elm = this;
//Find the parent tab element
var tab_elm = $(this).closest('#tabs > div');
//Really simple "loader"
tab_elm.html('<p>loading...</p>');
//Submit by ajax
my_cool_ajax_post(form_elm, tab_elm);
return false;
});
</script>
Disclaimer: Completely untested, so let me know...

How can i search for a specific row in a Database using PHP?

How can i make a search from the form in an HTML page display the result in the same html page? Am having an error when i try and run the code that says inputPackageID is not defined. How can i get to solve this. Seems like the variable is not being recognized from the form. Please help
Here is my code. If you dont understand my question you can ask me where you are not clear.
<div class="main">
<div class="col-md-12">
<div class="row">
<div class="container">
</div>
<div class="search center-block col-md-6" align="center">
<p>
Want to track your package? <br />
Enter your Package ID(PID)
</p>
<form method="post" action="trackShipment.php">
<div class="form-group">
<label class="sr-only" for="inputPackageID"></label>
<input type="search" name="inputPackageID" class="form-control edit-form-control" id="inputPackageID" placeholder="PID">
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" name="submit" />
</div>
</form>
</div>
<div class="col-md-8" align="center">
<h2>Well, Here is your package!</h2>
<?php
include '../includes/connection.php';
//include 'phpscripts/trackShipment.php';
$PackageID = $_GET['inputPackageID'];
$sql = "select * from package where p_id='$PackageID'";
?>
<table class="table table-striped">
<tr>
<th><span>PID</span></th>
<th><span>Customer ID</span></th>
<th>Name</th>
<th>Description</th>
<th>Destination Per KM</th>
<th>Type</th>
<th>Price/KG</th>
</tr>
</th>
<?php
foreach ($db->query($sql) as $count)?>
<tr>
<td>
<?php echo $count['p_ID']; ?>
</td>
<td>
<?php echo $count['cus_ID']; ?>
</td>
<td>
<?php echo $count['package_name']; ?>
</td>
<td>
<?php echo $count['package_description']; ?>
</td>
<td>
<?php echo $count['package_type']; ?>
</td>
<td>
<?php echo $count['destination_per_km']; ?>
</td>
<td>
<?php echo $count['price_per_kg']; ?>
</td>
<?php } ?>
</table>
</div>
</div>
It's showing you that it's not defined because your form uses a post method, and you're using a GET array.
$PackageID = $_GET['inputPackageID'];
change that to
$PackageID = $_POST['inputPackageID'];
Plus, use isset()
if(isset($_POST['inputPackageID'])){
$PackageID = $_POST['inputPackageID'];
}
since you're using your entired code inside the same page.
or !empty()
if(!empty($_POST['inputPackageID'])){
$PackageID = $_POST['inputPackageID'];
}
If you're using the same code inside the same file, you can use action="" and an extra conditional statement for your submit button.
if(isset($_POST['submit'])){...}
Seeing a comment of yours, this isn't the case then and you are using a seperate file, so we can scratch that.
However, if a GET method is what you really want to use, you will need to change your method to method="get" in your form. Using this method is unsafe, consult my footnotes.
Footnotes:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
"How can i make a search from the form in an HTML page display the result in the same html page?"
You can either use Ajax for this, or use action="".

Omit part of an HTML while using PHP

I'm trying to load part of a targeted URL ($url) into my HTML page, currently the $url page sends back a name, model, type and self recalculate tool - all of which live in a HTML TR tags.
Once I post my daily password from password.php than my users click on $url to get their daily inventory from it, again and i don't mean to be redundant, but the $url itself is provided to me by my clients and I don't want my users to be able to see all the links on that page - Only what pertain to their job.
Also rather than me creating password.php is there a way for me to "collect" this password from my daily outlook exchange email and post it to the header of the $url??
Many thx and I hope i was descriptive enough.
<html>
<head>
<title>Post Password</title>
</head>
<body>
<?php
$password = "";
?>
<form name="password" method="post" action="users.php">
<table border="0" cellspacing="0" cellpadding="2">
<tr>
<td>Paste the Daily Password</td>
<td><input type="text" maxlength=7 name="password"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
<html>
<head>
<title>First Page</title>
</head>
<body>
<?php
$url_append = "?secret=";
//$psk = $password;
$linktext = "Click here to get a Pre Shared Key";
$password = $_POST["password"];
$url = "http://example.subexample.xx.com/";
$url .= $url_append;
$url .= $password;
$final_url = $url;
// end base users
?>
<!--I took this form below from the URL that my client host-->
<!--His url have way more input than all_products-->
<!-- but that's the only one that I want to echo for my employees to use -->
<form name="form1" method="post" action="<?php echo htmlspecialchars($final_url);?>">
<table border="0" cellspacing="0" cellpadding="2">
<tr>
<td>Main Inventory</td>
<td><input type="text" maxlength=7 name="all_products"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
For sending POST through header take a look at this.
As for the omitting the parts of html, you can use alternative syntax like this
<?php if ($a == 5): ?>
<p>This will be omitted if condition is not true</p>
<?php endif; ?>
Similar can be used for for loop.
Read more on alternative syntax.

$_GET not working properly

i have a code in which i received two variable($isbn,$eno) from former page via form GET method but these two variables are not working if i am not echo out it on my page the code for the same is given below.
<?php
error_reporting(E_ALL);
require 'db/connect.php';
if(isset($_POST['generatereport']))
{
$isbn=$_GET['isbn'];
$eno=$_GET['eno'];
echo $eno; //if this is not done then i am not receiving data from database
echo $isbn; //if this is not done then i am not receiving data from database
$studentdata="select * from users where eno='$eno'";
if($studentresult=$db->query($studentdata))
{
$studentrow = $studentresult->fetch_assoc();
}
else
{
echo"fetching error";
}
$bookdata="select Lpad(isbn,'10','0') as isbn,book_name from book_data where isbn='$isbn'";
if($bookresult=$db->query($bookdata))
{
$bookrow = $bookresult->fetch_assoc();
}
else
{
echo"fetching error";
}
}
?>
<!doctype html>
<html lang='en'>
<head>
</head>
<body>
<div id='report'>
<table>
<tr><td><h3>Issue Report</h3></td></tr>
<tr><td><h4>Student details</h4></td></tr>
<tr><td>UNIQUE ID:<?php //random number here ?></td></tr>
<tr><td>Enrollment:<?php echo $eno; ?></td></tr>
<tr><td>Name:<?php echo strtoupper($studentrow['fname']);echo strtoupper( $studentrow['lname']); ?></td></tr>
<tr><td>Branch:<?php echo strtoupper($studentrow['branch']); ?></td></tr>
<tr><td>Semester:<?php echo $studentrow['sem']; ?></td></tr>
</table>
<hr/>
<table>
<tr><td><h4>Book details</h4></td></tr>
<tr><td>isbn:<?php echo $bookrow['isbn']; ?></td></tr>
<tr><td>Book Name:<?php echo strtoupper($bookrow['book_name']);?></td></tr>
</table>
<hr/>
<form action="script/issue.php?isbn=<?php echo $isbn;?>" method='post' id='report'>
<input id="btn_issue" type="button" value="Issue this Book"/>
<input id="btn_close" type="button" value="cancel"/>
</form>
</div>
</body>
</html>
You need to set attribute name to inputs in your form, after that you can access to value by GET or POST
Change form method:
<form action="script/issue.php?isbn=<?php echo $isbn;?>" method='get' id='report'>
<input name ='isbn' id="btn_issue" type="button" value="Issue this Book"/>
<input name ='eno' id="btn_close" type="button" value="cancel"/>
</form>
Or get your variables from post, like:
$isbn=$_POST['isbn'];
$eno=$_POST['eno'];
change your from method to get
<form action="script/issue.php?isbn=<?php echo $isbn;?>" method='get' id='report'>
or you can use $_REQUEST in php which can read either get or post
If you use method="POST", it meant you should use $_POST for your next process. Can use $_REQUEST also. But I think $_POST is more specifics for method POST. Please read the documentation of PHP about form method again.

Categories