Making Variables Global in PHP? - php

Need to make $courseInfo and $row global so that they can be used for printing the row details in the header DIV.
Don't have a clue how to do this. Any help would be great.
<?php
// Get Course ID From Link
$ID = mysql_real_escape_string($_REQUEST['ID']);
// Check the Course ID exists
$courseCheck = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
if (mysql_num_rows($courseCheck) == 1) {
$checkMember = mysql_query("SELECT * FROM CourseMembers WHERE CourseID = '".$ID."' AND UserID = '".$_SESSION['UserID']."'");
if (mysql_num_rows($checkMember) == 1) {
?>
<html>
<head>
<!-- Style Sheets -->
<link rel="stylesheet" href="style/reset.css" type="text/css" media=screen />
<link rel="stylesheet" href="style/style.css" type="text/css" media=screen />
</head>
<body>
<?php
if ($_SESSION['LoggedIn'] == 1){
$courseInfo = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
$row = mysql_fetch_assoc($courseInfo);
?>
<div id="container">
<div id="side">
<?php include("lib/sidebar.php"); ?>
</div>
<div id="main">
<div id="mainbox">
<div id="header"><b><?php echo $row['CourseName']; ?></b></div>
<p>Hello world, this is a test.</p>
</div>
</div>
</div>
<div class="clear"></div>
<?php
}
else {
echo "Not logged in.";
}
}
else {
echo "You are not a member of this Course";
}
}
else {
echo "No Course Found";
}
?>
</body>

I think they're already global. "PHP does not have a block-level scope."

You could store them in session variables, similarly to your $_SESSION['LoggedIn']

You could also use php variable $GLOBALS for making your variables visible in all scopes but I would not recommend it for this kind of task. Also, beware - $GLOBALS contains superglobals like $_POST and $_GET, you should keep that in mind, when ie. iterating over it. Furthermore - when you can access $_GET and $_POST in functions, that have smaller scope you still have to use $GLOBALS to access custom ones.
Example for this kind behaviour:
<?php
error_reporting(-1);
$GLOBALS['_customVar'] = 'foobar';
$GLOBALS['_GET']['id'] = 'myId';
function myFnc() {
echo $_customVar;
}
function myFnc2() {
echo $_GET['id'];
}
myFnc();
myFnc2();
?>

Related

PHP displaying unique data

currently I have a website with a basic login, I was just wondering how I would display a the name,skill and description of the unique user who is logged in.This is what I have done so far.I can only find articles on how to display data into table.This is the updated code:
<?php
include('session.php');
require 'config.php';
$sql = "SELECT * FROM profile";
$result = $conn->query($sql);
//echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="profile.css">
</head>
<body>
<ul>
<li>Home</li>
<li>PostJob</li>
<li>Find Job</li>
<li>How It Works</li>
<li>Notifications</li>
<li>Message</li>
<li>profile</li>
</ul>
<h1>Welcome To Bid4MyJob</h1>
<li>edit profile</li>
<div id="ProfilePage">
<div id="LeftCol">
<div id="Photo"></div>
<div id="ProfileOptions">
a
</div>
</div>
<div id="Info">
<p>
<strong>Name:<?php echo $row["name"]?></strong>
<!--<span>James</span>-->
</p>
<p>
<strong>Skill:<?php echo $row["skill"]?><</strong>
<!--span>James</span>-->
</p>
<!-- <p>
<strong>review:<?php /*echo $row["review"]*/?><</strong>
<span>james</span>
</p> -->
<p>
<strong>Description:<?php echo $row["description"]?><</strong>
<span>James</span>
</p>
<!--<p>
<strong>Name:</strong>
<span>james</span>
</p>-->
</div>
<!-- Needed because other elements inside ProfilePage have floats
<div style="clear:both"></div>-->
</div>
</body>
</html>
when the user successfully loggedin create a cookie and store their username or email whatever you used in that cookie. You have to do this stuff in your login.php file where you checks for username and password.
if(login success)
{
setCookie("username",value of username that you got from
user,'time()+3600','/');
echo "login successful";
}
After that in Profile you have write code like this;
<?php
$name=$_COOKIE['username'];
$sql=$conn->prepare("SELECT * from profile where username=?");
$stmt->bind_param('s', $name); // 's' specifies the variable type =>'string'
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
?>
After that you can display the inforamtion in your div like $row['username'] etc.
if $row[] come from a sql request, just add in your request something like :
$user = (...) your current user logged
(...)
select (...) where user = $user
You can use $_SESSION to identify people after login and store information about the person. A session variable saves data of a specific user across multiple pages.
A session id is stored in the user browser and that is used to identify the $_SESSION data of a person.
In your program you can easily do something like this:
<?php
session_start(); //before anything else
include('session.php');
require 'config.php';
$sql = "SELECT * FROM profile";
$result = $conn->query($sql);
//assuming $row contains the information from
$_SESSION["user"] = $row;
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="profile.css">
</head>
....
....
Now on another page, you could easily:
<?php
session_start();
if(isset($_SESSION["user"]) {
//logged in
$name = $_SESSION["user"]["name"];
} else {
//not logged in
}
?>
<html>
....
....

HTML inside of PHP variables

I am still very new to MySQL/PHP and am trying to make code that will loop through my whole SQL table. I was able to do that, to clean things up I wanted to use an html table to store the values in to make things look neater. I tried adding the HTML code into the string which gets printed at the bottom of the code in the HTML section, but the table borders do not show. What am I doing wrong and how can I fix this? Both code and screenshot of output are below:
<?php
include("connection.php");
$query= "SELECT * FROM schedule";
$result = mysqli_query($link, $query);
$scheduletext="<table>";
if($result = mysqli_query($link, $query)) {
while ($row=mysqli_fetch_array($result)) {
$scheduletext="<tr><td>".$scheduletext.$row[1]."</td>";
$scheduletext="<td>".$scheduletext.$row[2]."</td>";
$scheduletext="<td>".$scheduletext.$row[3]."</td>";
$scheduletext="<td>".$scheduletext.$row[4]."</td></tr>";
}
}
$scheduletext=$scheduletext."</table>";
?>
<html>
<head>
<title>TastySnack - Production Schedule</title>
<link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="tasty.css">
</head>
<body>
<div id="top">
<div id="top-left">
TastySnack Production
</div>
<div id="top-right">
<img id="logo" src="images/TastysnackLogo.jpg">
</div>
</div>
<div id="split"></div>
<div id="schedule">
<?php
print_r($scheduletext);
?>
</div>
</body>
</html>
Click Here For Screenshot of Output
As #mister martin said in comment use dot to concatinate your string
$scheduletext ="<table>";
if($result = mysqli_query($link, $query)) {
while ($row=mysqli_fetch_array($result)) {
$scheduletext .="<tr><td>".$scheduletext.$row[1]."</td>";
$scheduletext .="<td>".$scheduletext.$row[2]."</td>";
$scheduletext .="<td>".$scheduletext.$row[3]."</td>";
$scheduletext .="<td>".$scheduletext.$row[4]."</td></tr>";
}
}
$scheduletext .="</table>";

php MYSQL query "ORDER BY" not working

Forewarning: I'm sure my code is clunky and inefficient, please feel free to call me out on it. I'm fairly new at this.
I'm attempting to order my query results by a column, indicated as a result of a select input. The select input exists on feed.php which features include: 'feedphp2.php.
The select input auto-submits onchange with action="feedSort.php". feedSort.php takes the submitted value and redirects to feed.php?sort=submittedValue. Then the included feedphp2.php within feed.php takes the $_GET['sort'] value and pulls a query sorted by that column.
//feed.php
<?php
session_start();
if(!isset($_SESSION['userID'])) {
header('Location: login.html');
}
?>
<html>
<head>
<title>Title</title>
<link href="style.css" type="text/css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css
family=Josefin+Sans:400,100,300,600,700' rel='stylesheet' type='text/css'>
</head>
<body style="background-color:rgba(0,212,242,0.1)">
<div class="headerSmall">
<div class="container">
<a href="index.php"><img class="logoImgSmall"
src="images/logosmall2.png"></a>
<div class="navFeed">
<?php include 'usernameGet.php';?>,Log Out
List a Meal
Dashboard
</div>
</div>
</div>
<div class="container">
<div class="sort">
<form action="feedSort.php" method="POST">
<select name="sortForm" onchange="this.form.submit()">
<option value="">Sort By...</option>
<option value="user">By User</option>
<option value="dateAdded">By Date Added</option>
</select>
</form>
</div>
<?php include 'feedphp2.php'?>
</div>
</body>
</html>
space
//feedphp2.php
<?php
include 'MysqlConnect.php';
mysqli_select_db($conn,$dbname);
if (isset($_GET['sort'])) {
$sortBy = $_GET['sort'];
echo $sortBy;
$resultQuery = "SELECT * FROM meals
ORDER BY '$sortBy'";
} else {
echo 'sortBy is not set.';
$resultQuery = "SELECT * FROM meals
ORDER BY user";
}
$result = mysqli_query($conn, $resultQuery);
//Write to divs
while ($rows = mysqli_fetch_assoc($result)) {
$imgSrc = $rows['image'];
echo '<a href="meal.php?'.'mealID=';
echo $rows['ID'];
echo '">';
echo '<div class="entry">';
echo '<div class="foodPic">';
echo '<img src="';
echo $imgSrc;
echo '">';
echo '</div>';
echo '<p class="entryName">'.$rows['mealName'].'</p>';
echo '<p class="entryServ">'.$rows['mealQuan'].'</p>';
echo '<p
class="entryPrice">$'.$rows['mealDollars'].'.'.$rows['mealCents'].'</p>';
echo '<img class="servingsIco" src="images/servings.png">';
echo '<p class="user">'.$rows['user'].'</p>';
echo '</div>';
echo '</a>';
}
?>
space
//feedSort.php:
<?php
session_start();
$sortBy = $_POST['sortForm'];
header ("Location: feed.php?sort=".$sortBy."");
?>
Columns within my table exist for both user and dateAdded and sort perfectly when explicitly provided within the query ie: SELECT * FROM meals
ORDER BY user. While provided through a PHP variable however:
Where $sortBy = user returns the exact same sort order as $sortBy = dateAdded.
I appreciate any help you might provide.
you using $_POST method to pass the value and using $_GET method to retrieve it . and change the $sortby without quotes. edit these lines in your feedphp2.php
<?php
include 'MysqlConnect.php';
mysqli_select_db($conn,$dbname);
if (isset($_POST['sort'])) {
$sortBy = $_POST['sort'];
echo $sortBy;
$resultQuery = "SELECT * FROM meals
ORDER BY $sortBy";
} else {
or use $_REQUEST[],Method which will retrieve both get and post method
<?php
include 'MysqlConnect.php';
mysqli_select_db($conn,$dbname);
if (isset($_REQUEST['sort'])) {//request method
$sortBy = $_REQUEST['sort'];//
echo $sortBy;
$resultQuery = "SELECT * FROM meals
ORDER BY $sortBy";
} else {

PHP - echo doesn't seem to work right

I have this function that gets a table from another site by finding each row of that table and, providing that row isn't a duplicate, echos it to my site. I want to add my own row to the bottom though so I thought it would be as simple as just echoing
<tr><td>TEXT</td></tr>
as you can see below. But when I load the page, this row isn't added. Anyone know what the cause may be?
Here is the website if that helps.
function getStats(){
$page = file_get_html(getPageURL());
$rows = array();
echo "<table id=statsTable>";
foreach($page->find('html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr/') as $key=>$element) {
if(!in_array($element, $rows)){
$rows[$key]=$element;
echo $rows[$key-1];
}
}
echo "<tr><td>Viewing old updates will be added soon</td></tr></table>";
}
Main problem was in key offset, when you work with arrays it's better to use keys in this case. So in order to that I've changed the in_array to array_key_exists, because we want to check if key exists, but if you want to work with element you have to know its key.
function getStats(){
$page = file_get_html(getPageURL());
$rows = array();
echo "<table id=statsTable>";
foreach($page->find('html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr/') as $key => $element) {
if(!array_key_exists($key, $rows)){
$rows[$key] = $element;
/* Echo only when it exists */
if(array_key_exists($key-1, $rows)){
echo $rows[$key-1];
}
}
}
echo "<tr><td>Viewing old updates will be added soon</td></tr></table>";
}
?>
<?php
include "getData.php";
include "simple_html_dom.php";
?>
<!DOCTYPE HTML>
<html>
<head>
<title>KSA Flight Tracker</title>
<link rel="stylesheet" type="text/css" href="KSAStyle.css"/>
</head>
<body>
<div id="page">
<div id="leftPanel">
<p id="missionsHeader">Active Missions</p>
<?php getList(); ?>
</div>
<div id="mainPanel">
<p id="infoHeader">
<?php getTitle(); ?>
</p>
<div id="info">
<center>
<?php
getInfo();
getImage();
getMap();
getStats();
?>
</center>
</div>
</div>
</div>
</body>
</html>

Let users visit other users (profiles) in my own written social community?

The thing I'm asking for is how the users can visit other users profile.
The past week I have been scripting a social network I'm doing, and I'm kind of stuck right now.
I don't know where to start and read or anything.
So I'm asking you guys to kindly help me =)
Im thinking of the url to be like user.php?id=123 looking and get user you are visiting to show up instead of "you" wich is at user.php!
Live demo: http://social.swipper.org
EDIT #2:
Here's the current code i got inside user.php :
<?php
session_start();
if($_SESSION['username']) {
include "config.php";
$username = $_SESSION['username'];
$fetcher = mysql_query("SELECT * FROM userinfo WHERE username='$username'");
while ($data = mysql_fetch_assoc($fetcher)){
$firstname = $data['firstname'];
$lastname = $data['lastname'];
$gender = $data['gender'];
}
// get user's profile image
if (file_exists("users/$username/profile.jpg")) {
$userPhoto = "<img class='pic' src='users/$username/profile.jpg' width='90%' height='30%' />";
}
elseif (!file_exists("users/$username/profile.jpg")) {
$userPhoto = "<img class='pic' src='http://www.uavmedia.com/portal/images/no-user.jpg' width='90%' height='30%' />";
}
// the user's profile image is fetched
// henter profil text
$file = "users/$username/bio.txt";
$contents = file($file);
$profile_text = implode($contents);
// ferdig å hente profil text, vil nå echo ut profil siden.
// henter profil stilsett
$file2 = "users/$username/style.css";
$contents2 = file($file2);
$profile_style = implode($contents2);
// ferdig å hente profil stilsett.
echo
"
<!doctype html>
<html lang='en'>
<head>
<title>Social FW</title>
<meta name='Description' content='A Social network for everyone. Come join us!' />
<meta name='Keywords' content='Social, Network, Framewerk, Framework, FW, Open-Source, Free' />
<link rel='stylesheet' type='text/css' href='user_files/style.css' media='screen' />
<link rel='stylesheet' type='text/css' href='SFW_files/style2.css' media='screen' />
<style type='text/css'>
$profile_style
</style>
<link rel='icon' href='SFW_files/favicon.ico' media='screen' />
<script type='text/javascript' src='http://code.jquery.com/jquery-latest.js'></script>
<script type='text/javascript' src='SFW_files/scripts/login.js'></script>
</head>
<body>
<div id='top'>
<h1>Swipper.org</h1>
</div>
<div id='side-menu'>
<ul>
<li><a href='user.php'><b>".$username."</b></a></li><br/>
<li><a href=''>Inbox</a></li>
<li><a href=''>Guestbook</a></li>
<li><a href=''>Friends</a></li>
<li><a href=''>Pictures</a></li><br />
<div id='showOptions'><li><a href='#'>Edit Profile</a></li></div>
<div id='editOptions' style='display:none;'>
<pre class='user_info'><b>></b><a href='changeText.php'>Edit Profile Text</a>
<b>></b><a href='changeCss.php'>Edit Stylesheet(CSS)</a>
<b>></b><a href='changeProfilePic.php'>Change Profile Image</a></pre>
</div><br />
<a href='logout.php'><b>Logout</b></a>
</ul>
</div>
<div id='side-left'>
<!-- START USER PIC --!>
<center>
$userPhoto<br />
</center>
<!-- END USER PIC --!>
<!-- START USER INFO --!>
<br />
<h3><pre class='user_info'>User Info</pre></h3>
<pre class='user_info'>Name: ".$firstname." ".$lastname."<br />Sex : $gender</pre>
<!-- END USER INFO --!>
</div>
<div id='box_center'>
<h2 style='font-size:30px;' align='center'>$username</h2>
<hr />
<br />
$profile_text
</div>
<div id='footer'>
<p align='center'>Swipper.org © All rights reserved. 2010-2012</p>
</div>
</body>
</html>
";
}
else {
die("You need to login first or register. You can register/login <a href='index.php'>here</a>!");
}
?>
and when the url is like: user.php?id=3 i want to get the user with userid 3 to show up, and get user #3's information instead of the "user" who wants to visit other people.
Are you listing all the users some where? if you are the href needs to be something like
<?php
$sql = mysql_query("SLECET * FROM userinfo");
while ($row = mysql_fetch_assoc($sql)){
echo "<a href='users.php?id=" . $row['id'] . "'>"
}
then in users.php
<?php
if(isset($_REQUEST['id'])) {
if(is_numeric($_REQUEST['id'])){
$uid = $_REQUEST['id'];
$sql = mysql_query("SELECT * FROM userinfo WHERE id='" . $uid . "' LIMIT 1");
}
} else {
$sql = mysql_query("SELECT * FROM userinfo WHERE username='" . $_SESSION['username'] . "' LIMIT 1");
}
then later your html can use that with a fetch_assoc($sql)
<table>
<tr>
<td><?php echo $row['username'] ?>'s Profile</td>
</tr>
</table>
simple example. but i think you get the picture, message me on FB for more on this Stian
This should be your answer:
if (isset($_GET['username']){
$username = mysql_escape_string($_GET['username']);
}else{
$username = $_SESSION['username'];
}
$fetcher = mysql_query("SELECT * FROM userinfo WHERE username='$username'");
if (mysql_num_rows() == 0){
$username = '';
echo 'Username not found'; die();
}
Make your query like
$userID = $_GET['id'];
$fetcher = mysql_query("SELECT * FROM userinfo WHERE userID='$userID'");
and you can accordingly show data for any user with the valid user ID as given in url.
if profile can be viewed without login too then there is no need of session and if its compulsory only check if isset or not. if you are passing username in url as
user.php?user=test1
then your query will be like
$username = $_GET['user'];
$fetcher = mysql_query("SELECT * FROM userinfo WHERE username='$username'");
Hope now its more clear to u.

Categories