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
Related
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
When the user submits the form, the form information is posted to a php file and the php file redirects the user straight away to the next webpage once the form is submitted by using the header function. I have already validated the form using HTML and Javascript however the PHP has validation in it so that any errors that get past the Javascript and HTML are identified and the user is notified, however this is not possible at the minute as the user is redirected before they are notified.
How would I identify the user if the PHP locates an error?
Is it necessary as will the only errors be by people who are intentionally trying to be malicious?
My code is:
<?php
header("location: (next webpage)");
if(isset($_POST['submit'])){
$data_missing = array();
if(empty($_POST['email_banned'])){
// Adds name to array
$data_missing[] = 'Email';
} else {
// Trim white space from the name and store the name
$email_banned = trim($_POST['email_banned']);
}
if(empty($_POST['notes'])){
// Adds name to array
$data_missing[] = 'Notes';
} else {
// Trim white space from the name and store the name
$notes = trim($_POST['notes']);
}
if(empty($data_missing)){
require_once('mysqli_connect.php');
$query = "INSERT INTO banned_emails (id, email_banned, created_on, notes) VALUES ( NULL, ?, NOW(), ?)";
$stmt = mysqli_prepare($dbc, $query);
//i Interger
//d Doubles
//s Everything Else
mysqli_stmt_bind_param($stmt, "ss", $email_banned, $notes);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if($affected_rows == 1){
echo 'Student Entered';
mysqli_stmt_close($stmt);
mysqli_close($dbc);
} else {
echo 'Error Occurred<br />';
echo mysqli_error();
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}
} else {
echo 'You need to enter the following data<br />';
foreach($data_missing as $missing){
echo "$missing<br />";
}
}
}
?>
Thanks :)
You can use $_SESSION to store errors, and retrieve them later.
$_SESSION['errors'] = array('an error message', 'a second error message');
Then in the script the user has been redirected to :
while($err = array_shift($_SESSION['errors'])){
?>
<p class='p_error'><?=$err?></p>
<?php
}
table name - user_table
i try to save and update value from single Save button.
but I can not understand how to merge save and update code in 'if else' using certain condition.
Below is my save code :
<?php
require_once('includes/config.php');
$errors = array();
$Admin = new admins;
if(isset($_POST['save']))
{
$errors = $Admin->validate_cms_user_table();
if(!count($errors))
{
$table = $Admin->user_table;
$fields_func = array ('password' =>"md5('{$_POST['password']}')");
unset ($_POST['password']);
if($Admin->save_advance($table,$_POST,$fields_func))
{
$_SESSION['message'] = "User Created Successfully";
header("Location:user_master.php");
exit;
}
}
}
?>
Update code
if($Admin->save($Admin->user_table,$_POST,"id=".$_GET['id']))
{
$_SESSION['message'] = "Updated Successfully";
header("Location: user_master.php");
exit;
}
Update Condition
if(!isset($_GET['catid']))
{
//Then Save Code
}
Else
{
//Update Code
}
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");
I am trying to create two separate sessions- one for if the user is admin and another if the user is author. $type stored type as enum (can be either author or admin). But my code is creating author session even for admin. I am new to PHP and MySQL . can somebody tell me where the error is in my code.
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
My welcome.php is as below
<?php
session_start();
?>
<html>
<body>
<h2>Welcome.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
}
?>
</body>
</html>
Thank You so much in advance.
Try to use roles for your permissions.
In general you have just one session. I mean you don't have two variables called _SESSION.
With the concept of roles you can simply check if a user has the permission to do something.
You have to call session_start() in the first part of the code, before register the var $_SESSION['type'] in the session
No your code seams fine, I think.
I don't see where you are calling the database
And what you have in there
So here is how you trouble shoot
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
echo $type . '<br />';
}
OR
echo '<pre>';
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
print_r($info);
}
echo '</pre>';
If you never see admin in there, and it must be 'admin' not Admin or ADMIN; then the problem is in your database. You don't have admin as admin defined, or spelled right.
By the way. see how nicely I formatted that. It's easier to read that way.
Coders wont look at your code if you don't do that.
Try using session_regenerate_id(); method to create different session ids.