How to directly send php to another page? - php

I am new to programming and am using html, mySQL and PHP to try and make a user name and password setup for user profiles. I then want to display a customized page to the user.
The problem is, after I check to see if they are in the database, or not in the database, I can't figure out how to send them directly to a new page.
I've tried using a function I found on google called header() but I keep getting an error. I tried resolving it by making sure I had no output to the screen before using the header() function, and I'm pretty sure by now that I don't. I don't actually know what the problem is and am trying to find another way to do this or just find an answer with header(). Anyhow, here's my code:
<?php
require "connect_to_mysql_and_test_connection.php";
//use the variable $db to access the database
?>
<html>
<head>
<title>User Login</title>
<h2>Login:</h2>
</head>
<body>
<!--this makes a form to take the user input. the input of username and password. the submit buttons value is always submitted to $_POST-->
<form method="post">
Create user name:<br>
<input type="text" name="username" /><br>
Create password:<br>
<input type="text" name="password"/><br>
<input type="submit" name="submit"/><br>
</form>
<?php
$compare_username="";
$compare_password="";
//get the username and password fields from the database and store it in a variable
$username_password_fields=$db->query("SELECT username, password FROM users");//mysql object
//get number of rows
$rows= $username_password_fields->num_rows;
//create a while loop to go through each row.
while($rows >=1){
//iterate through each array returned by fetch_assoc to see if the username already exists
foreach($username_password_fields->fetch_assoc() as $key=>$value){
//echo $key . $value . "<br>";
//************check to see if the username exists****************
if ($value === $_POST['username']){
$compare_username=$value;
}
else if ($value === $_POST['password']){
$compare_password=$value;
}
}
//check to see if the username matches the password
$rows -= 1;//decrement the rows remaining
if ($compare_username != "" and $compare_password != ""){
//write code to send them to their custom page
**header("Location:http://jasongriffore.atwebpages.com/myfirstworkingsite.php")<--This is the problem. please help!**
echo "Ding ding ding a match!";
return;
}
else if ($compare_username != ""){
echo "This user name exists but the password is incorrect";
//they can try again on the same page
return;
}
}
//if after running the while loop they didn't get sent to their custom page, the must be new!
echo "Let's create a new account for you!";
//enter code to add a new user to the database
echo print_r($_POST, true);
?>

Use header() function:
header('Location: mypage.php');
And be sure there is no output sent to the browser before you do so as I can see there is because your HTML <form> is before your PHP treatment. Change that.

I would recommend using ob_start() and ob_end_flush() to buffer your output to the browser. You can read a little more about this here. The main reason you want to do this is because, the header tag requires that no output has been sent to the browser yet. By echoing out <html><head>... it's already sent data to the client, therefore no more headers can be sent (They are headers after all, intended to head the output.) ob_start() will buffer (Or store) everything until you're ready to output it, and will allow you later on to send headers because the output has not been sent to the browser yet.
<?php
require "connect_to_mysql_and_test_connection.php";
//use the variable $db to access the database
//Buffer the output
ob_start();
?>
<html>
<head>
<title>User Login</title>
<h2>Login:</h2>
</head>
<body>
<!--this makes a form to take the user input. the input of username and password. the submit buttons value is always submitted to $_POST-->
<form method="post">
Create user name:<br>
<input type="text" name="username" /><br>
Create password:<br>
<input type="text" name="password"/><br>
<input type="submit" name="submit"/><br>
</form>
<?php
$compare_username="";
$compare_password="";
//get the username and password fields from the database and store it in a variable
$username_password_fields=$db->query("SELECT username, password FROM users");//mysql object
//get number of rows
$rows= $username_password_fields->num_rows;
//create a while loop to go through each row.
while($rows >=1){
//iterate through each array returned by fetch_assoc to see if the username already exists
foreach($username_password_fields->fetch_assoc() as $key=>$value){
//echo $key . $value . "<br>";
//************check to see if the username exists****************
if ($value === $_POST['username']){
$compare_username=$value;
}
else if ($value === $_POST['password']){
$compare_password=$value;
}
}
//check to see if the username matches the password
$rows -= 1;//decrement the rows remaining
if ($compare_username != "" and $compare_password != ""){
//write code to send them to their custom page
header("Location:http://jasongriffore.atwebpages.com/myfirstworkingsite.php");
return;
}
else if ($compare_username != ""){
echo "This user name exists but the password is incorrect";
//they can try again on the same page
return;
}
}
//if after running the while loop they didn't get sent to their custom page, the must be new!
echo "Let's create a new account for you!";
//enter code to add a new user to the database
echo print_r($_POST, true);
//Write the output to the browser
ob_end_flush();
?>

Use javascript :
<script>window.location = 'http://jasongriffore.atwebpages.com/myfirstworkingsite.php';</script>

Related

How to display error messages on redirect?

It's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages that come from a file separate to the html/php form.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
All the research I've done hasn't gotten me far. I understand that sending the headers isn't good practice. I looked at ob_open (php function-I think it was called) and couldn't figure out how to properly use it. I couldn't find a question on here that satisfied the conditions I'm trying to meet either.
Any help is certainly appreciated.Thank You
EDIT: This is not a duplicate of 'Passing error messages in PHP'.
-------While the idea is similar, they are 'Passing error messages in PHP' before the headers are sent. Therefore it's not the same.
Store the error in a session and echo it on the destination page.
Put session_start() at the top of the code of the form.php page. Like this:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
Then replace the echo error with:
$_SESSION['error'] = 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
Use this in your conditions instead of the echo. Then in the form.php page:
if (isset($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
The unset makes sure that the error is repeated.
An HTTP Redirect causes a new HTTP request. Since php is stateless, it cannot natively support remembering a message to display to a specific user in another request. In order to get around this limitation, you would need to use a stateful storage mechanism (session or cookies), or pass the error message along to the next request via query string parameter. The usual way this is handled is by using session storage to save flash messages.
Here is a library that can make it a bit easier for you https://github.com/plasticbrain/PhpFlashMessages
Set session of error and display on the page on which you are redirecting

PHP Form validation server side, Display error on page, Display outputs on other page

I'm trying to validate a form using server-side, but the problem is, I can't display the error message and inputs. To explain it in details:
Have a form that can post inputs
Validate the data eg,. if empty, display error on the page, else proceed to the target page
form page, this is where I validate and display
<?php
?>
<?=$firstErr?>
<form method="POST" action="">
<input type="text" name="firstname" />
<input type="text" name="secondname" >
<input type="submit" name="submit" >
</form>
target page
if(isset($_POST['submit']))
{
$first = $_POST['firstname'];
$second = $_POST['secondname'];
if($first == "" && $second== "")
{
echo "<script language='javascript'>window.location = 'main.php';</script>";
$firstErr .= '<p class="error">Username should be alpha numeric characters only.</p>';
}
else
{
echo $first;
echo $second;
}
}
That is because you have already been redirected to the page before the line execution.
Instead add an alert like this.
if($first == "" && $second== "")
{
echo "<script>alert('Username should be alpha numeric characters only.');</script>"; //<-- Added here
echo "<script language='javascript'>window.location = 'main.php';</script>";
}
It's because the redirect occurs and the PHP isn't executed. What you can do is set a GET param in your redirect.
echo "<script language='javascript'>window.location = 'main.php?error=1';</script>";
And on main.php
if(isset($_GET['error']) && $_GET['error'] == 1) { do code ... }
When you need to go back to main.php the javascript simply loads that page.
As far as I know, you will have to implmenent some sort of a checking method that will store your error codes on sessions or cookies and then write a check to display the messages if there are errors. You will have to clear the errors saved once main.php is loaded by the way.
Or you can pass on the error messages through $_GET by modifying your javascript.
Your javascript could look like
window.location = "main.php?err=1";
You can set your main.php to
if(isset($_GET['err'])) {
//Your logic to check the error message number and display text goes here
}
Ideal would be to verify on the client side using javascript/jquery but since you mentioned this to be a server side verification you will have to either use a framework that has all the foundation laid for such kind form validation (using a framework has many pros and cons so I am not sure if this feasible to you. Just putting it out there), or write your own small logic to check and revert back to the main page with the error codes.

create a simple PHP login / logout system

This is for an assignment, however ive done a lot on my part to research but i feel like ive reached a wall. I need to create a page where the user can go to sign in (login.php), once they're signed in they're redirected to the index page. The link they clicked to login should be replaced with a logout link.
however with all this noted, first things first i do get into the session part and ive echoed the variables and retrieved them however it doesnt do the redirect to the index.php also when i manually click to the index.php after logging the session variables are empty. what am i doing wrong here???
so this is my php code in the login.php
$found = false;
//read the read.txt until the end of file
while(!feof($inputFile) && $found == false)
{
$line = fgets($inputFile);
// replace the special charater within the lines by there proper entity code
$lineArray = preg_split("/\,/", (string)$line);
if(strcmp($_REQUEST['email'],$lineArray[2]) && strcmp($_REQUEST['pwd'],$lineArray[4]))
{
$found = true;
echo "<script>alert(' FOUND!')</script>";
session_start();
$myuseremail=$_REQUEST['email'];
$mypassword= $_REQUEST['pwd'];
$_SESSION['login_email']=$myuseremail;
$_SESSION['login_pwd']=$mypassword;
setcookie("login_email", $_SESSION['login_email'], time()+60*60*24);
setcookie("login_pwd", $_SESSION['login_pwd'], time()+60*60*24);
header('Location:index.php');
}
}
fclose($inputFile);
and then in my index.php i contain this code before the body of my html
<?php
session_start();
if(isset($_SESSION['login_email']) && isset($_SESSION['login_pwd']))
{
$user_check=true;
echo $_SESSION['login_email'];
}
else
{
$user_check=false;
}
?>
within the index.php i also have this code lined in for my links
<li>Home</li>
<li>Register</li>
<?php
if ($user_check){
print "<li><a href='logout.php'>Logout</a></li>";
}
else{
print "<li><a href='login.php'>Login</a></li>";
}
?>
<li> Link 4</li>
I found some errors in your code, all coming down to the same point: You cannot send any custom headers after you have began outputting other data.
Where have you done this?
Here:
echo "<script>alert(' FOUND!')</script>";
session_start();//session_start() sends a cookie to the clients machine.
//How are cookies sent to clients browsers? Through headers.
And here:
setcookie("login_email", $_SESSION['login_email'], time()+60*60*24);
setcookie("login_pwd", $_SESSION['login_pwd'], time()+60*60*24);
header('Location:index.php');
Personally, I think your code is a complete mess. Because I have nothing better to do, I'll re-write it for you, explaining each step as I go along.
Let's begin:
So the first thing you want to work on is your text file, which stores all the user details.
Instead of using plain lines or whatever, we should use JSON to split users details, from user to user.
So here's what the text file will look like with two users in it:
{"navnav":{"username":"navnav","pass":"deb1536f480475f7d593219aa1afd74c"},"user2":{"username":"user2","pass":"deb1536f480475f7d593219aa1afd74c"}}
Notice how I've also used the username as keys too and how I've hashed the password. So we call this file user.txt and store it somewhere safe.
Now, for the login page, we shall simply get the data through the POST method, compare it, set sessions and tell the user to go somewhere else (redirect them).
session_start();//need to start our session first, of course
//check if any login data has been posted our way
if ( isset($_POST['login']) && !empty($_POST['username']) && !empty($_POST['password']) )
{
//assign input data to temp vars
$username = $_POST['username'];
$password = md5($_POST['password']);//notice how I hash the password
// get the data fro the text file
$userData = file_get_contents('path to your text file');
//decode the json data to an assoc array
$userData = json_decode( $userData , true );
//check if the user exists
if ( array_key_exists( $username , $userData ) === false )
{
echo 'the username '.$username.' is invalid.';//notify the user
exit();//bye bye
}//end of user does not exist
//so now we know the user name exists (because we've got to this line)
//we shall compare with the password
if ( $userData['$username']['password'] !== $password )
{
echo 'Your password is incorrect';//notify the user
exit();//bye bye
}//end of incorrect password
else
{
//time to set sessions and stuff
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
//send the redirect header
header('Location: index.php');
exit();
}//end of password is correct
}//end of login data has been sent
That's all your login code, but you need your html form setup correctly for the right things to be posted with the right names. So use this html form:
<form action="login.php" method="post" name="login" target="_self" id="login">
<p>
<label for="username">Username</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="password">Password</label>
<input type="text" name="password" id="password" />
</p>
</form>
That's your login page completely sorted.
Now for your index.php:
As you did before, check if the user is logged in and throw the status is in a var:
session_start();//resume your session (if there is one) or start a new one
//set default user status
$userStatus = false;
if ( isset($_SESSION['username']) && isset($_SESSION['password']) )
{
$userStatus = true;
}//end of user is logged in
For your HTML login/logout:
<li>Home</li>
<li>Register</li>
<?php
if ($userStatus === true){
echo "<li><a href='logout.php'>Logout</a></li>";
}
else{
echo "<li><a href='login.php'>Login</a></li>";
}
?>
<li> Link 4</li>
And there you have it.
Let me know if you have any problems.
One more thing:
This is far from secure. Why? You're using text files, you're using text files and you're using text files.
EDIT:
To separate the JSON data by user, simply edit the text file manually (see my comment).
Or you could just paste this into your text file:
{"navnav":{"username":"navnav","pass":"deb1536f480475f7d593219aa1afd74c"},
"user2":{"username":"user2","pass":"deb1536f480475f7d593219aa1afd74c"}}
Do you see how there is no \n in the above? Because I just created a new line manually (by just hitting enter). \n will make the JSON code invalid, so that's why you should avoid it. This method just means if you have to create new users, and you need a new line for each user, then you will have to do it manually.
Actually your script does the opposite of what you are probably intended to:
strcmp does compare both parameters, but it does not return a boolean value.
First thing to do 'd be to change that line to:
if ($_REQUEST['email'] === $lineArray[2] && $_REQUEST['pwd'] === $lineArray[4]) {
First of all, never send a header after some output has occurred, i.e. when you do echo "<script>alert(' FOUND!')</script>"; this is considered output and a header will be generated by PHP and your header line later on will be ignored.
Try using header without any output being sent first, this should fix the redirect problem.
As far as why the session information is wiped, try the following line on the redirect:
header('Location:index.php?'.SID);
It shouldn't be required but its worth giving it a shot.

Retaining values in forms fields when validation of data fails

I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>

Post Back response from PHP to javascript

I'm new to forms and post data ... so I don't know how solve this problem!
I've a php page (page1) with a simple form:
<form method="post" action="/page2.php">
<input type="search" value="E-Mail Address" size="30" name="email" />
<input type="submit" value="Find E-Mail" />
</form>
How you can notice ... this form post the 'email' value to the page2. In the page2 there is a small script that lookup in a database to check if the email address exist.
$email = $_POST['email'];
$resut = mysql_query("SELECT * FROM table WHERE email = $email");
.
.
.
/* do something */
.
.
.
if($result){
//post back yes
}
else{
//post back no
}
I don't know how make the post back in php! And how can I do to the post back data are read from a javascript method that shows an alert reporting the result of the search?
This is only an example of what I'm trying to do, because my page2 make some other actions before the post back.
When I click on the submit button, I'm trying to animate a spinning indicator ... this is the reason that I need to post back to a javascript method! Because the javascript function should stop the animation and pop up the alert with the result of the search!
Very thanks in advance!
I suggest you read up on AJAX.
Here's a PHP example on W3Schools that details an AJAX hit.
Hi i think you can handle it in two ways.
First one is to submit the form, save the data in your session, check the email, redirect
back to your form and display the results and data from session.
Like
session_start();
// store email in session to show it on form after validation
$_SESSION['email'] = $_POST['email'];
// put your result in your session
if ($results) {
$_SESSION['result'] = 'fine';
header(Location: 'yourform.php'); // redirect to your form
}
Now put some php code in your form:
<?php
session_start();
// check if result is fine, if yes do something..
if ($_SESSION['result'] == 'fine) {
echo 'Email is fine..';
} else {
echo 'Wrong Email..';
}
?>
More infos : Sessions & Forms
And in put the email value back in the form field
<input type="search"
value="<?php echo $_SESSION['email']; ?>"
size="30"
name="email" />
Please excuse my english, it is horrible i know ;)
And the other one the ajax thing some answers before mine !
As a sidenote, you definitly should escape your data before using it in an SQL request, to avoid SQL injection
As you are using mysql_* functions, this would be done with one of those :
mysql_escape_string
or mysql_real_escape_string
You would not be able to post in this situation as it is from the server to the client. For more information about POST have a look at this article.
To answer your question you would want to do something like this when you have done your query:
if(mysql_num_rows($result)){ //implies not 0
$data = mysql_fetch_array($result);
print_r($data);
}
else{
//no results found
echo "no results were found";
}
The print_r function is simply printing all the results that the query would have returned, you will probably want to format this using some html. $data is just an array which you can print a single element from like this:
echo $data['email'];
I hope this helps!
<?php
echo " alert('Record Inserted ');"
OR
echo " document.getElementByID('tagname').innerHtml=$result;"
?>
OR
include 'Your Html file name'

Categories