php returning a EMPTY echo. HOW / WHY? - php

I am having a very difficult time to figure out WHY I am getting this empty echo. I am debugging and I see all the values in the right place but it does not echo!
<body>
<div class='wrapper'>
<div id='message'>
<h2>Mail Sent Successfully!</h2>
<p>We will be in touch soon.</p>
<?php
// Echo session variables that were set on previous page
if (isset($_POST['first_name'])) {
session_unset();
session_destroy();
$_SESSION['name'] = isset ($_POST['first_name']) ? $_POST['first_name'] : "";
$_SESSION["favcolor"] = "Green ";
echo "name: " . $_SESSION['name'] . ".<br>";
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
}
?>
</div>
<form method="POST" id="myform" class="myform" title="Apply Title" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="background-color:#FFFFFF;">
<fieldset>
<div>
<label class="title">First Name</label>
<input type="text" name="first_name" id='first_name' class="required" minlength="2" data-msg-required="Please enter your first name" maxlength='128' value="<?PHP if(isset($_POST['first_name'])) echo htmlspecialchars($_POST['first_name']); ?>">
</div>
<p id="invalid-first_name" class="error_msg"></p>
</fieldset>
<fieldset>
<div>
<label class="title">Your employer's company name.</label>
<input type="text" name="employer" id='employer'>
</div>
<p id="invalid-employer" class="error_msg"></p>
</fieldset>
<input type="button" name="submit" id="submit_app" class="sub" value="submit"/>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src='http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js'></script>
<script src='http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js'></script>
<script type="text/javascript" src="formToWizard.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").formToWizard({ submitButton: 'submit_app' });
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#invalid-' + element.attr('name'));
}
});
});
</script>
While debugging the code I can see all the value that just got typed. But once you submit the form it does not echo!

You are trying to echo non existent session. Put session_start() before assigning variables.
<?php
// Echo session variables that were set on previous page
if (isset($_POST['first_name'])) {
session_unset();
$_SESSION['name'] = $_POST['first_name'];
$_SESSION['favcolor'] = "Green";
echo "name: " . $_SESSION['name'] . ".<br>";
echo "Favorite color is " . $_SESSION['favcolor'] . ".<br>";
}
?>
EDIT:
I cleaned your code a little bit, try now. Dont destroy session, you can simply unset it if u need to. Also, im not sure what are you trying to do with $_SESSION['name'] = isset ($_POST['first_name']) ? $_POST['first_name'] : ""; so i changed that.

Related

PHP to MYSQL form validation and database insertion with PHP_SELF and php process

I'm trying to use a php form saved on the artistRegister.php below and process it with the file at the bottom named processArtist.php .
I can't find the proper way to populate the fields in case there's an error and when I submit it to the database, I get an empty record on the database.
I'm populating a dropdown list on the navigation bar at header.php and using the same code to connect to the database, so it's not a database communication problem, since I'm able to create new empty records on the submit button press.
Tried several ways to make it work but would appreciate any help debugging the problem at hand.
Thank you advance.
***artistRegister.php***
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
//define page title
$title = 'Members Page';
//include header template
require('layout/header.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php if(isset($title)){ echo $title; }?></title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div class="container-fluid">
<div class="col-xs-3">
</div>
<div class="col-xs-6">
<?php
// define variables and initialize with empty values
$artistName = $artistLabel = $websiteAddress = $facebookAddress = $youtubeAddress ="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["artistName"])) {
$nameErr = "Enter Artist name";
}
else {
$artistName = $_POST["artistName"];
}
if (empty($_POST["artistLabel"])) {
$labelErr = "Enter Label name";
}
else {
$artistLabel = $_POST["artistLabel"];
}
}
?>
<form class="form" method="POST" action="processArtist.php">
<div class="form-group">
<label for="artistName">Artist Name:</label>
<input type="text" class="form-control" id="artistName" value="<?php echo htmlspecialchars($artistName);?>">
<span class="error" style="color: red"><?php echo $nameErr;?></span><br>
<label for="artistLabel">Artist Label:</label>
<input type="text" class="form-control" id="artistLabel" value="<?php echo htmlspecialchars($artistLabel);?>">
<span class="error"><?php echo $LabelErr;?></span><br>
<label for="websiteAddress">Artist Website:</label>
<input type="text" class="form-control" id="websiteAddress" value="<?php echo htmlspecialchars($websiteAddress);?>">
<label for="facebookAddress">Artist Facebook:</label>
<input type="text" class="form-control" id="facebookAddress" value="<?php echo htmlspecialchars($facebookAddress);?>">
<label for="youtubeAddress">Artist Youtube:</label>
<input type="text" class="form-control" id="youtubeAddress" value="<?php echo htmlspecialchars($youtubeAddress);?>">
<br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
<div class="col-xs-3">
</div>
</div>
</body>
***processArtist.php***
<?php
$host="localhost";
$username="some_user_with_access";
$password="the_user_password";
$db_name="artist_management";
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump($_POST);
$artistName=$_POST['artistName'];
$artistLabel=$_POST['artistLabel'];
$websiteAddress=$_POST['websiteAddress'];
$facebookAddress=$_POST['facebookAddress'];
$youtubeAddress=$_POST['youtubeAddress'];
$sql="INSERT INTO artists (artistName, artistLabel, websiteAddress, facebookAddress, youtubeAddress)
VALUES
('$artistName', '$artistLabel', '$websiteAddress', '$facebookAddress', '$youtubeAddress')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);

Populate a certificate with information from a form on another page in php

I am creating e-learning that users will take a quiz. Upon submit they will be sent to the results page where it will show them their scores. If the user passes a link will pop up to a certificate they can print out. I cannot get the certificate to populate variables(first name, last name, etc).
Here is what I have:
index.php (home page where they take the quiz and fill out a form)
<form id="form1" name="form1" method="post" action="results.php" onsubmit="return validateForm() ;">
<label>Last Name:
<input type="text" name="lname" id="lname" tabindex="1" />
</label>
<label>First Name:
<input type="text" name="fname" id="fname" tabindex="2" />
</label>
<label>Title:
<input type="text" name="title" id="title" tabindex="3" /><br/><br/>
</label>
<?php
$quiz = new Quiz( $questions );
echo $quiz->renderQuiz();
?>
<input name="Submit" type="submit" value="Submit" />
</form>
On results.php (page that shows results and link to certificate)
<?php
$ip = $_SERVER['REMOTE_ADDR']; // employee's Ip address
$time = date("d/m/y : H:i:s", time()); // current timestamp
$email_string = create_email_string( $force_email, $_POST['email_to'] );
$questions_correct = array();
$info_to_save = array( $_POST['lname'], $_POST['fname'], $_POST['title'];
// Grades the quiz
$score = (string)round( ( count($questions_correct) / count($questions)*100), 2 );
$variables = array();
$variables['fname'] = $_POST['fname'];
$variables['lname'] = $_POST['lname'];
$variables['test_name'] = $test_name;
$variables['score'] = $score;
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test Results</title>
<link rel="stylesheet" type="text/css" href="./stylesheets/quiz_stylesheet.css" />
</head>
<body>
<div id="white">
<div id="header">
<img src="./images/ucdheader.jpg" width="1000" id="header" /img>
</div>
<div id="mainContent">
<h1><span>You Scored <?php echo $score ?>%</span>
<br><?php if ($score >= 80)
echo "<a href=certificate.php >Print Certificate</a>
"?></h1>
<p>Below are your results for <?php echo $test_name; ?>. In order to pass this quiz, you must score 80% or better. If you would like to try again, click the following link.</p>
<a href='<?php echo $test_page_name ?>'>Try again</a>
<p>These results were sent to the following addresses: </p>
<ul>
<?php
$all_emailed_to = explode( "; " , $email_string);
foreach ($all_emailed_to as $email) {
echo "<li>" . $email . "</li>";
}
?>
</ul>
</div>
</div>
</body>
</html>
On certificate.php
<title>Certificate</title>
</head>
<body>
<div id="white">
<div class="btn-group btn-group-lg">
<a role="button" class="btn btn-default" href="#" data- function="print">Print Certificate</a>
</div>
<div class="certificate">
<img src="images/cert.png" width="820" height="527" id="cert" />
<div class="name">
<?php $variables['fname'] . " " . $variables['lname'] . ?>
</div>
<div class="course">
<p></p>
</div>
<div class="completion_date">
<?php $variables['time']; ?>
</div>
</div>
</div>
</body>
</html>
Thank you!
You are not passing any variables to the certificate.php page. There are several options of passing data between php pages such as:
1) Sessions
2) $_POST
3) $_GET
The easiest option in your code is using the $_GET variable. Simply use this line of code in results.php:
echo "<a href=certificate.php?fname={$variables['fname']}&lname={$variables['lname']} >Print Certificate</a>"?></h1>
Than in certificate.php retrieve the data by using:
<?php echo $_GET['fname'] . " " . $_GET['lname'] . ?>
Note 1: you will need to urlendode() the variables in the link in case someone puts special chairs in their name/last name
Note 2: It's a hackable approach. An employee could print a certificate with just any name/last name by calling a prepared url.
The best approach would be to rewrite all three pages to use Sessions: http://php.net/manual/en/features.sessions.php
Either you go for Kamran's approach and build a hidden form which will send by POST the information needed in the certificate page, either you go for a database oriented model(i.e. save users and their results and then retrieve those information to generate the certificate).
The first way is pretty unsafe since you can change the values of the fields using Firebug and send dirty unexpected input if you don't test the values.
In results.php store necessary values in SESSION:
$info_to_save = array( $_POST['lname'], $_POST['fname'], $_POST['title'], time);
//Start session if not started
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['certInfo'] = $info_to_save;
Then use it in certificate.php like this:
//Start session if not started
if (!isset($_SESSION)) {
session_start();
}
$lname = $_SESSION['certInfo'][0];
$fname = $_SESSION['certInfo'][1];
$title = $_SESSION['certInfo'][2];
$time = $_SESSION['certInfo'][3];

Retrieving data from textarea php

I cannot seem to retrieve the data input into this text area. Also I know this code may not be secure, but I am just beginning with php.
echo '<tr><td align=right>Description:</td><td><textarea name=description form=description cols=100 rows=5></textarea></td></tr>';
$descriptionToSend = $("#description").val()
DBSubmit("INSERT INTO Conference (conferenceid,description,submission_due,review_due) VALUES ('".$_POST['conferenceName']."', '" . $descriptionToSend . "','" .$_POST['submitdeadline'] . "','" .$_POST['reviewdeadline']. "')");
Are you mixing up jquery with php ?
First, the <textarea> should reside in a <form>
After the form is submitted to php, you can access the data sent with $_REQUEST['description'] so you would have
$descriptionToSend = $_REQUEST['description'];
<html>
<head>
<title>Test</title>
</head>
<body>
<?php $name = 'nick';
?>
<form action="Test.php">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
About Me: <textarea name="about" rows="5" cols="10"><?php echo $comment; ?></textarea><br/>
Click Me: <input type="submit" vaule="submit">
</body>
</html>
Use $comment to set text and then just retrieve value using $_GET['about'] in next page
<html>
<body>
<?php
$about = $_GET['about'];
echo $about;
?>
</body>
</html>

PHP $_SESSION data not saving from page to page

I'm beating my head against the wall right now. I've been fiddling with this for hours, and I can't seem to figure it out.
My sessions data isn't saving when I navigate from one page to another. I've set this up in WAMP, BTW.
The cookies are being saved, and the sessions data only works when I reset it at the beginning of EVERY script. I'm not quite sure what to do here. It's probably something ridiculously stupid, but any input is greatly appreciated.
my login script:
<?php
include('../partials/_header.php');
include('includes/connectvars.php');
if(!isset($_SESSION['id'])) { //logged in?
if(isset($_POST['submit'])) { // form submitted?
if(!empty($_POST['email']) && !empty($_POST['password'])) { /* Check to make sure post isn't empty in case of JS override/disable */
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = sha1(mysqli_real_escape_string($dbc, trim($_POST['password'])));
/* query DB */
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($dbc, $query) or die ("There was an error with your mySQL query:" . mysqli_error($dbc));
if(mysqli_num_rows($result)==1) { /* Check that matching row exists in users for login */
$row = mysqli_fetch_array($result);
$_SESSION['id'] = $row['id']; // set the session info
$_SESSION['type'] = $row['type'];
$_SESSION['name'] = $row['f_name'];
setcookie('id', $row['id'], time()+ (60*60*24*30));
setcookie('type', $row['type'], time()+ (60*60*24*30));
setcookie('name', $row['f_name'], time()+ (60*60*24*30));
$home_url = '/'; //redirect not working with $_SERVER variable in WAMP. keep an eye for the future
header('Location: '.$home_url);
mysqli_close($dbc);
} else { /* if no match in database ask to resubmit login info or register */?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#login_form").validate();
});
</script>
<div class="span-24 colborder">
<form id="login_form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label class="error">Your email and/or password are incorrect. </label><br />
<label class="error">If you haven't already signed up, feel free to <a href="user_registration.php" > register</a> </label><br />
<input type="text" name="email" id="email" value="" class="email required" placeholder="example#example.com"/> <br />
<input type="password" name="password" id="password" class="required" value="" /> <br />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<?php
}/* end conditional to check $rows array for username pw match */
} /* end conditional to check that form isn't blank */
else { /* If form is blank ask to resubmit or register */?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#login_form").validate();
});
</script>
<div class="span-24 colborder">
<form id="login_form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label class="error">You must enter your email and password if you wish to continue.</label><br />
<input type="text" name="email" id="email" value="" class="email required" placeholder="example#example.com"/> <br />
<input type="password" name="password" id="password" class="required" value="" /> <br />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<?php
} // end else to resubmit in case of blank form
} /* end check if form has been submitted */ else{ /* prompt for login if page visited but login form not submitted */ ?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#login_form").validate();
});
</script>
<div class="span-24 colborder">
<form id="login_form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label class="error">You must be logged in to do that!.</label><br />
<input type="text" name="email" id="email" value="" class="email required" placeholder="example#example.com"/> <br />
<input type="password" name="password" id="password" class="required" value="" /> <br />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<?php
}
} /* end check if cookie isset */ else { //redirect if cookies & session is already set
$home_url = '/';
header('Location: '.$home_url);
}
?>
<?php include('partials/_footer.php'); ?>
this is my header (which includes the set session variable if cookie isset)
<?php //set session if isset cookie but not session
session_start();
if(!isset($_SESSION['id'])) {
if(isset($_COOKIE['id']) && isset($_COOKIE['name']) && isset($_COOKIE['type'])) {
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['name'] = $_COOKIE['name'];
$_SESSION['type'] = $_COOKIE['type'];
}
} //end if !isset session verify
?>
and an example of the menu output depending on their session id:
<?php
if(isset($_SESSION['type']) && $_SESSION['type'] == "rnr") { //start special runner menu options
?>
<ul class="main_menu">
<li id="how_it_works" class="main_menu"><a class="main_menu" href="/user/bid_task.php">Bid on a task</a></li>
<li id="our_runners" class="main_menu"><a class="main_menu" href="/our_runners.php">Our Runners</a></li>
<li id="login" class="main_menu"><a class="main_menu" href="/user/my_account.php">My account</a></li>
<li id="register" class="main_menu"><a class="main_menu" href="/user/logout.php">Logout</a></li>
</ul>
<?php } /* end runner menu */ ?>
Thanks in advance.
The header file is included before the setcookie function is called in your login script. Based on what I see, the cookie is not set at the time you do this condition check:
if(isset($_COOKIE['id']) && isset($_COOKIE['name']) && isset($_COOKIE['type']))
And because of that it never get inside the condition statement and following lines do not get executed in the header file:
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['name'] = $_COOKIE['name'];
$_SESSION['type'] = $_COOKIE['type'];

error correction for the PHP code

I have written the following code and not able to figure out the errors in it..
It not poping out any errors ..what it does is that it just stays on the html page
whats wrong in it?
html page
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function get(){
$("#button1").click(function(){
$.post('script_1.php', { name: form.name.value },
function(output) {
$('#age').html(output).show();
}) ;
});
}
$("#button2").click(function(){
$('form#myForm').attr({action: "script_2.php"});
$('form#myForm').submit();
});
});
</script>
</head>
<body>
<form id="myForm" method="post">
doi: <input type="text" name="name"/>
<input type="button" id="button1" value ="Get" onclick="get();"/>
<input type="button" id="button2" value="Submit to script 2" />
title:<input type="text" name="title"/>
</form>
<div id="age"></div>
</body>
</html>
script_1.php for the first button is
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
//connect to database
$name = mysql_real_escape_string($_POST['name']);
if ($name==NULL)
echo "please enter an id!";
else
{
$age= mysql_query("SELECT title FROM parentid WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
if ($age_num_rows==0)
echo "id does not exist";
else
{
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$abc_output= "Existing data of the record <br />";
$abc_output .="Title: " . $row['title'] . "<br />" ;
$abc_output .="Report No: " . $row['reportno'] . "<br />" ;
$abc_output .="URL: " . $row['calc_url'] . "<br />" ;
$abc_output .="Institution: " . $row['institution'] . "<br />" ;
}
}
echo $abc_output;
}
}
?>
script_2.php is another php file
with update operation in database.
//title form is only used in script_2.php for updation.
script_1.php is used for displaying already present elements in DB.
Help appreciated.
There is a slight problem with your HTML and Javascript code. The way you declared the click functions, was improper. Try this:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$.post('script_1.php', { name: $('input[name$="name"]', '#myForm').val() },
function(output) {
$('#age').html(output).show();
});
});
$("#button2").click(function(){
$('form#myForm').attr({action: "script_2.php"});
$('form#myForm').submit();
});
});
</script>
</head>
<body>
<form id="myForm" method="post">
doi: <input type="text" name="name"/>
<input type="button" id="button1" value ="Get"/>
<input type="button" id="button2" value="Submit to script 2" />
title:<input type="text" name="title"/>
</form>
<div id="age"></div>
</body>
</html>
Here are your two SQL queries that you asked for:
$age= mysql_query("SELECT title FROM parentid WHERE id =(select id from parentid where name='$name')");
$sql ="SELECT * FROM parentid WHERE id = (select id from parentid where name='$name')";
a few things pop into mind, first, where you have this:
if ($name==NULL)
echo "please enter an id!";
it should be more like
if (empty($name))
echo "please enter an id!";
next, you have this:
$name = mysql_real_escape_string($_POST['name']);
and it should me more like
if(isset($_POST['name'])) $name = mysql_real_escape_string($_POST['name']);
else echo "they didnt use the form.";
and finally, i do not see and code to actually connect to a database.
Okay, i have a solution for you.
here is my example form
<form action='posted.php' method='post'>
<input type='submit' name='b1' value='Button 1' /><br />
<input type='submit' name='b2' value='Button 2' /><br />
</form>
and here is 'posted.php'
<?php
if(isset($_POST['b1'])) echo 'Button 1';
if(isset($_POST['b2'])) echo 'Button 2';
?>
when you press 'Button 1', the php gives 'Button 1', and the same goes for button 2.

Categories