I am trying to find out how to have multiple scripts within one php file, and run Certain scripts only when a certain link is clicked on (or some other input from a user). For example, the default output Of profile.php is the user's "wall", but when they click "info" on the profile.php page (the page reloads because I'm not using JavaScript and that's okay for now) the main content area would now display the user's info (as printed by a script within the original profile.php file) how is this done?
3
-
1Do you want to clone Facebook?Martin.– Martin.2011-11-16 13:16:11 +00:00Commented Nov 16, 2011 at 13:16
-
Have you read about 'include' or 'require' ?gustavotkg– gustavotkg2011-11-16 13:18:50 +00:00Commented Nov 16, 2011 at 13:18
-
@gustav it seems he's looking for a conditionYour Common Sense– Your Common Sense2011-11-16 13:21:45 +00:00Commented Nov 16, 2011 at 13:21
Add a comment
|
4 Answers
That's fairly easy. Using only one php file, you can have many "actions" that displays some stuff depending on what you need. Take a look of this simple source code (save it as "file.php" or use the name you like and edit the "a" tags. I've included the name of the file as some browsers do not work correctly when the link starts with "?".
<h3>Sections</h3>
<a href="file.php?action=home">Home</a>
<a href="file.php?action=wall">Wall</a>
<a href="file.php?action=profile">profile</a>
<?php
if (!isset($_GET['action']) {
$action = "home";
}
else {
$action = $_GET['action'];
}
switch($action) {
case 'wall':
display_wall();
break;
case 'profile':
display_profile();
break;
case 'home':
default:
display_home();
break;
}
function display_wall() {
echo("Wall");
// Do something
}
function display_profile() {
echo("Profile");
// Do something
}
function display_home() {
echo("Home");
// Do something
}
Tweak that code a bit to fill your needs.
2 Comments
user502019
Could you explain what is happening here: if (!isset($_GET['action']) { $action = "home"; } else { $action = $_GET['action']; }
Sergio Moura
To prevent errors, I check if the user is passing a parameter to the "action" variable. if you access ..../file.php the "$_GET['action']" will not be set, so, it defaults to the "home" action. If the user accesses ..../file.php?action=wall the "$_GET['action']" variable will contain 'wall', and thus, the $action variable will be set accordingly.
You should learn something about predefined variables $_GET, $_POST and for the later use, $_COOKIE
<?php
if ($_GET['clicked'] == "info") {
//show user's info
}
else{
//show another info
}
?>
<a href="?clicked=info">Click to see info</a>
1 Comment
Sumair Zafar
The above code will help you to run certain script on specific action on the same page