Aufwind
Aufwind

Reputation: 26288

PHP VS. HTML. Passing a value from html to php

I have a action.php which does some processing involving a MySQL-Database. In action.php I generate a variable

$author

with a string in it. When the script terminates it calls test.php by

header('Location: ../test.php');

Now while test.html is shown, I want to display the content of the stringvariable

$author

in a html-element. Like

<h2>echo $author;</h2>

How do I achieve that? Thank you for any responses in advance.

Upvotes: 3

Views: 173

Answers (6)

Anorgan
Anorgan

Reputation: 303

You could put the contents of the $author in a session:

<?php
// action.php
session_start();
// Your code here

$_SESSION['author'] = $author;

// Redirect to test.php

<?php
// test.php
session_start();

echo '<h2>'. $_SESSION['author'] .'</h2>';

See:

  1. session_start

Upvotes: 1

CdB
CdB

Reputation: 4908

In your action.php save your variable in session like this: $_SESSION['author'] = $author;

Then, in your test.php file you can use <h2><?php echo $_SESSION['author']; ?></h2>

Don't forget to start both .php files with calling session_start();

Upvotes: 1

niczak
niczak

Reputation: 3917

Sounds like you are trying to pull author data from a database and display it in test.php. If so there is no need to "pass" the data to test.php, just grab data in test.php.

test.php

<?php
// Open DB handle
// Do query, get results.
// Store results in array ($aRes)
// Close DB handle
?>

<html>
.
.
.
  <body>
  <h2><?php echo $aRes['author'];?></h2>
  .
  .
  </body>
</html>

That is a very basic and obviously fairly pseudo template but hopefully it will give you a better idea of the relationship between server-side data and HTML.

Upvotes: 0

Devin Crossman
Devin Crossman

Reputation: 7592

you could store $author in a session variable or on the action.php page output a form with a hidden input with the value of $author and then submit it to test.php

to use session variables don't forget session_start(); and then $_SESSION['author'] = $author

Upvotes: 1

dgilland
dgilland

Reputation: 2748

You'll need to either store the value of $author in $_SESSION or in a cookie.

See session.php

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318718

Use a template engine, e.g. Twig.

While you can use PHP itself as a template engine (include() your file and use <?=$var?> or <?php echo $var; ?> in it), using a real template engine is usually nicer as you won't even think about moving actual business logic into your templates when you have a good template engine.

Upvotes: 0

Related Questions