Trying to display this data in the diary post page solely based on the Session variable.
The Session variable is already declared in the php/ functions file.
The data foreign key is already linked between the User ID in the accounts table and the diary post table in PHP my admin
I just need an Inner join query of some description to only show the data based on Session.
Functions declared at the top of diary page
<?php
include("php/functions.php");
$userID = $_SESSION["userID"];
?>
The functions file
<?php
if(session_id() == '') {
session_start();
}
if(!isset($_SESSION['myEmail'])){ //if login in session is not set
header("Location: login.php");
}
if (!isset($_SESSION['myEmail'])) {
echo" <a href='login.php'";
}
else {
$myFName = $_SESSION['userFirstName'];
}
Where I need to display the posts based on Session variable
<?php
// index.php
include 'mysql.php';
echo '<h1>My Positive Experience Diary</h1>';
echo "<em>Post 10 Positive Recent Experiences</em><hr/>";
$result = mysql_safe_query('SELECT * FROM posts ORDER BY date DESC');
if(!mysql_num_rows($result)) {
echo 'No posts yet.';
} else {
while($row = mysql_fetch_assoc($result)) {
echo '<h2>'.$row['title'].'</h2>';
$body = substr($row['body'], 0, 300);
echo nl2br($body).'...<br/>';
echo 'Read More | ';
echo '<hr/>';
}
}
echo <<<HTML
+ New Post
HTML;
?>
The mysql.php where the diarypost page is getting its data.
<?php
// mysql.php
function mysql_safe_string($value) {
$value = trim($value);
if(empty($value)) return 'NULL';
elseif(is_numeric($value)) return $value;
else return "'".mysql_real_escape_string($value)."'";
}
function mysql_safe_query($query) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
return mysql_query(vsprintf($query,$args));
}
function redirect($uri)
{
if (!headers_sent())
{
header('Location: '.$uri);
exit;
}
else
{
echo '<script type="text/javascript">';
echo 'window.location.href="'.$uri.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$uri.'" />';
echo '</noscript>'; exit;
}
}
#mysql_connect('localhost','########','########');
#mysql_select_db('########');
What it looks like posting all the data from the database not based on User ID
enter image description here
Related
Im currently filling a label with a session variable, however i need to use the label data later (send it to another label), or create a new session to do so. However, when i attempt to access the first label, or the session that ive set its tells me its not set. So im assuming the data in the first label is showing but its not actually there?
//this is how im creating the first label
<?php
include_once "dbcon.php";
//PERFORMING CHECK IF ALL REQUIRED SESSION VARIABLES ARE SET
if (isset($_SESSION['s_score1'], $_SESSION['s_score2'], $_SESSION['t_team1'], $_SESSION['t_team2'])) {
$team1 = $_SESSION['t_team1'];
$team2 = $_SESSION['t_team2'];
$score1 = $_SESSION['s_score1'];
$score2 = $_SESSION['s_score2'];
if ($score1 == $score2) {
header("Location: tables.php?table=draw"); //CHECKS IF MATCH IS A DRAW, CANNOT BE A DRAW
exit();
}else {
if ($score1 > $score2){
echo $_SESSION['t_team1'];
}else {
echo $_SESSION['t_team2'];
}
}
}else {
echo "-";
}
?>
//this is how im printing it
<label name="round2-team1" class="round2-teams">
<?php include_once "action/winner-script.php";?>
</label>
the issue appears when i try to use this label above, creating a session variable with it, or moving it to a new label is impossible, its like it doesnt exist, even though i can see it on the page???
<?php
include_once "dbcon.php";
//PERFORMING CHECK IF ALL REQUIRED SESSION VARIABLES ARE SET
if (isset($_SESSION['s_score9'], $_SESSION['s_score10'], $_SESSION['t_team9'], $_SESSION['t_team10'])) {
$team1 = $_SESSION['t_team9'];
$team2 = $_SESSION['t_team10'];
$score1 = $_SESSION['s_score9'];
$score2 = $_SESSION['s_score10'];
if ($score1 == $score2) {
header("Location: tables.php?table=draw"); //CHECKS IF MATCH IS A DRAW, CANNOT BE A DRAW
exit();
}else {
if ($score1 > $score2){
echo $_SESSION['t_team9'];
}else {
echo $_SESSION['t_team10'];
}
}
}else {
echo "-";
}
?>
This is the script, here i am taking my two labels that are displaying on the page, im determining the winner, and then im displaying the session variable which won the game in a different label on the same page. however, when i try using
<?php
if (isset($_SESSION['t_team9'])) {
echo $_SESSION['t_team9'];
}else {
echo "somethings wrong";
}
?>
anywhere on the page where my labels lie, i just get the error something went wrong
ATTEMPTED FIX:
<?php
include_once "dbcon.php";
//PERFORMING CHECK IF ALL REQUIRED SESSION VARIABLES ARE SET
if (isset($_SESSION['s_score13'], $_SESSION['s_score14'], $_SESSION['result'], $_SESSION['result2'])) {
$team1 = $_SESSION['result'];
$team2 = $_SESSION['result2'];
$score1 = $_SESSION['s_score13'];
$score2 = $_SESSION['s_score14'];
if ($score1 == $score2) {
header("Location: tables.php?table=draw"); //CHECKS IF MATCH IS A DRAW, CANNOT BE A DRAW
exit();
}else {
if ($score1 > $score2){
$team1 = $_SESSION['result'];
$_SESSION['result5'] = $team1;
}else {
$team2 = $_SESSION['result2'];
$_SESSION['result5'] = $team2;
}
}
}else {
echo "-";
}
?>
Looking to add a UserID based on session variable to this post method.
I can display the diary posts based on the Session ID but want to actually add the User's ID into the corresponding table everytime an entry is posted.
I've included pictures of the database below and the Insert Query that already adds posts.
The diary and tblUseraccount are already linked using foreign keys
PHP functions
<?php
if(session_id() == '') {
session_start();
}
if(!isset($_SESSION['myEmail'])){ //if login in session is not set
header("Location: login.php");
}
if (!isset($_SESSION['myEmail'])) {
echo" <a href='login.php'";
}
else {
$myFName = $_SESSION['userFirstName'];
}
The code I want to insert the UserID too
<?php
// post_add.php
if(!empty($_POST)) {
include 'mysql.php';
if(mysql_safe_query('INSERT INTO posts (title,body,date,) VALUES (%s,%s,%s)', $_POST['title'], $_POST['body'], time()))
echo 'Entry posted. View';
else
echo mysql_error();
}
?>
The mysql.php portion
<?php
// mysql.php
function mysql_safe_string($value) {
$value = trim($value);
if(empty($value)) return 'NULL';
elseif(is_numeric($value)) return $value;
else return "'".mysql_real_escape_string($value)."'";
}
function mysql_safe_query($query) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
return mysql_query(vsprintf($query,$args));
}
function redirect($uri)
{
if (!headers_sent())
{
header('Location: '.$uri);
exit;
}
else
{
echo '<script type="text/javascript">';
echo 'window.location.href="'.$uri.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$uri.'" />';
echo '</noscript>'; exit;
}
}
#mysql_connect('localhost','######','#######');
#mysql_select_db('######');
enter image description here
enter image description here
Firstly you need to set UserId in session
when you make the user login you can add the user id in session like you have added userFirstName
After that you can just start sessions in your file and then get the userId from session when you want to insert a post
session_start();
if(!empty($_POST)) {
include 'mysql.php';
$userId = $_SESSION['UserID']; //or whatever is your key in session where you store the user id
if(mysql_safe_query('INSERT INTO posts (title,body,date,UserID) VALUES (%s, %s, %s, %s)', $_POST['title'], $_POST['body'], time(), $userId)){
echo 'Entry posted. View';
}else{
echo mysql_error();
}
}
Also I noticed that your are using mysql_query to run your queries. You should use mysqli_query or PDO because mysql_query is deprecated in PHP 5.5 and it is removed in PHP 7.
You can read more in php page here
i starting with php and i want get session object in login form, then, i want show values the object session in a php web page but session object not read their values object.
my php file:
try {
$userLogin = new userDto();
$userLogin->setUsername($_POST["txtUsername"]);
$userLogin->setPassword($_POST["txtPassword"]);
if (UserDao::validateLogin($userLogin)) {
//if true, the method validateLogin load other values object in data access layer
//i tried with print_r($userLogin) and show all values (name,age,ocupation, profile etc....).. works
session_start();
if ($userLogin->getIdProfile() == 1) {
$_SESSION["userClient"] = $userLogin;
include_once '../Pages/MenuClient.php';
} else {
$_SESSION['adminUser'] = $userLogin;
include_once '../Paginas/MenuAdmin.php';
}
} else {
echo 'No exist';
}
} catch (Exception $ex) {
echo $ex->getMessage();
}
php web page:
<?php
include_once '../../Dto/UserDto.php';
$dto = new UserDto();
if(isset($_SESSION["userClient"])) {
$dto = $_SESSION["userClient"];
echo 'Exist user'; --> works!!
echo '<script type="text/javascript">alert("'+$dto->getName()+'");</script>'; --> not work
else {
echo '<script type="text/javascript">alert("no found");</script>';
}
?>
<label><?php echo $dto->getName()?></label> --> not work
<label value="<?php echo $dto->getName()?>"></label> --> not work
I have the codes to search autocomplete from MySQL and the match query can be clicked and direct me to a new page. How can i have the result of the clicked queries to be displayed in the new page w/out using any URL from database because I need to avoid using lots of HTML files. Thank you.
<p id="searchresults">
<?php
// PHP5 Implementation - uses MySQLi.
// mysqli('localhost', 'yourUserbookTitle', 'yourPassword', 'yourDatabase');
$db = new mysqli('localhost', 'root', '', 'book');
if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
$query = $db->query("SELECT * FROM bookinfo WHERE bookTitle LIKE '%" . $queryString . "%'");
if($query) {
// While there are results loop through them - fetching an Object.
// Store the category id
$bookTitle = 0;
while ($result = $query ->fetch_object()) {
if($result->bookTitle != $bookTitle) { // check if the category changed
echo '<span class="category">'.$result->bookTitle.'</span>';
$bookTitle = $result->bookTitle;
}
echo '<a href="'.$result->url.'">';
echo '<img src="search_images/'.$result->bookimage.'" alt="" />';
$bookTitle = $result->bookTitle;
if(strlen($bookTitle) > 35) {
$bookTitle = substr($bookTitle, 0, 35) . "...";
}
echo '<span class="searchheading">'.$bookTitle.'</span>';
$author = $result->author;
if(strlen($author) > 80) {
$author = substr($author, 0, 80) . "...";
}
echo '<span>'.$author.'</span></a>';
}
echo '<span class="seperator">Nothing interesting here? Try the sitemap.</span><br class="break" />';
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
?>
</p>
I don't know if I get your problem right, but if you need to display a new page with the selected book data/review/comments, I would add :
echo '<span>'.$author.'</span></a>'; /* after this line */
echo '<span>Read more > click here</span>'; /* where $bookID id the ID column in your DB */
Then, on the new page, retrieve data from DB according to $bookID value and display it...
I got user login system where user page has its own id in URL. for eg. xxx/profile.php?id=1
My question is: how to prevent logged user from writing other user id in URL and entering his site ?
here is the code of file profile.php:
session_start();
require 'config2.php';
require_once 'user.class.php';
if (!user::isLogged()) {
echo '<p class="error">Przykro nam, ale ta strona jest dostepna tylko dla zalogowanych u?ytkowników.</p>';
}
else {
$id = $_GET['id'];
$userExist = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM users WHERE id = '$id'"));
if ($userExist[0] == 0) {
die ('<p>Przykro nam, ale u?ytkownik o podanym identyfikatorze nie istnieje.</p>');
}
$profile = user::getDataById ($id);
echo '<h1>Profil u¿ytkownika '.$profile['login'].'</h1>';
echo '<b>ID:</b> '.$profile['id'].'<br />';
echo '<b>Nick:</b> '.$profile['login'].'<br />';
echo '<b>Email:</b> '.$profile['email'].'<br />';
echo '<b>Obiekt:</b> '.$profile['obiekt'].'<br />';
echo '<b>Typ obiektu:</b> '.$profile['typ'].'<br />';
echo '<b>Kod pocztowy:</b> '.$profile['kod'].'<br />';
echo '<b>Adres:</b> '.$profile['adres'].'<br />';
echo '<b>Poczta:</b> '.$profile['poczta'].'<br />';
echo '<b>Tel. stacjonarny:</b> '.$profile['tels'].'<br />';
echo '<b>Tel. komórkowy:</b> '.$profile['telk'].'<br />';
echo '<b>Adres strony internetowej:</b> '.$profile['www'].'<br />';
echo "<img src ='wyslane/$profile[photo]'";
}
and here's user_class.php:
<?php
class user {
public static $user = array();
public function getData ($login, $pass) {
if ($login == '') $login = $_SESSION['login'];
if ($pass == '') $pass = $_SESSION['pass'];
self::$user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE login='$login' AND pass='$pass' LIMIT 1;"));
return self::$user;
}
public function getDataById ($id) {
$user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE id='$id' LIMIT 1;"));
return $user;
}
public function isLogged () {
if (empty($_SESSION['login']) || empty($_SESSION['pass'])) {
return false;
}
else {
return true;
}
}
public function passSalter ($pass) {
$pass = '$###$##$'.$pass.'q2#$3$%###';
return md5($pass);
}
}
?>
I've got also my main page code here:
if (user::isLogged() == $_GET['id']) {
$user = user::getData('', '');
echo '<p>You are logged '.$user['login'].'!</p>';
echo '<p>You may see your profil or wylogować</p>';
}
else {
echo '<p>You are not logged.<br />Zaloguj się lub zarejestruj jeśli jeszcze nie masz konta.</p>';
}
I tried, what Ryan advised but it ( page) worked only when I double clicked the profile link, otherwise link sent me again to the login page.
Instead of passing the ID of the user through the URL ($_GET) try and set a $_SESSION variable with the ID of the user when he logs in.
Then you can just go to xxx/profile.php and read the $_SESSION var to find out the id of the user whose profile you want to to display.
Now I don't know how you retrieve the current logged-in user's id, but say for example you can get it from user::loggedInID() - you would just match this against the id of the profile being accessed.
For example:
if(user::loggedInID() == $_GET['id']) {
/* Allow profile to be edited */
} else {
/* Unable to edit profile */
}
As a side note, your database is extremely vulnerable with queries like so:
mysql_query("SELECT COUNT(*) FROM users WHERE id = '$id'")
Seeing as $id is retrieved from the query string, without being sanitized, the query is open to injection.
I advise not only sanitizing your query input to begin with, but also using mysqli_* functions instead of mysql_* functions (due to deprecation). Even better, use prepared statements.
While logging in just store the logged in user ID to a session variable like $_SESSION['Loggedusr'] and in each page at starting check this
session_start();
if($_SESSION['Loggedusr'] != $_GET['id'])
header("Location: loginpage.php");