displaying html report of session user id - php

In my admin section, I want the user to be able to click a button and a HTML report to display all fields from all tables with the user id that is set in that session.
So $user_id = intval($_SESSION['user_id']);
Would the button be something like:
<?php
if (isset($_POST['doReport'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$query = ("SELECT user_id FROM users WHERE user_id = '$user_id');
}
// redirect to report page
header('Location: report.php?id=' . $user_id);
?>
<p align="center">
<input name="doReport" type="submit" id="doThesisReport" value="View Report">
Also, what would be the best way to lay it out in the report page as I have 7 tables.
I am looking for a quick easy fix
Thank you!

You have a mistake: " char missed at the end of $query declaration.
I don't understand your trouble. If you want to use $_SESSION['user_id'], you can use it at any page without passing it in url.
And please don't put several questions in one.

The good way to achieve this would be :
Make a button witch redirects to a new page, say "report.php".
Now create the following logic for redirect page:
Fetch the USER-ID from session using the code you've used above.
Make the database connection on this page.
You forgot to use mysql_select_db(); to select the database.
Write the query like :
$query = ("SELECT user_id FROM users WHERE user_id = '$user_id'");
// you left "
Fire the query using $result=mysql_query($query); Note that the result from database is saved into $result.
You can use tables to display data as per you liking but quick way would be to use print_r($result)
Close the connection using mysql_close();
Hopefully since the question is not clear, I've posted the basic logic.
EDITED : forgot to put query in code block.

Related

Output database information in my html content

Im trying to display a "welcome, {first name}" to my website, but im not sure how to pull that info from my database to my page, i have looked at multiple other questions like this but i dont really follow what they want the people to do.
Here is some example code i have in a div on my html page, i want to draw their name if signed in, and nothing if they arent signed in. I was using this code to see if i could get the name to appear in the div as just to figure out how it works but im stuck.
<?php
if (isset($_SESSION['userId'])) {
echo "<p>You're logged in!</p>";
}
else{
echo "<p>You're logged out!</p>";
}
?>
thanks for any help :)
Assuming the user is already authenticated, and you know the user ID,
<?php if($_SESSION['auth']) { << condition >> } ?>
you might wanna create a connection to your database and make query to extract the name,
$conn = new mysqli($servername, $username, $password, $database);
$query = 'SELECT username FROM tablename WHERE user_id = '.$user_id;
$username = $conn->query($query);
and display it.
<? $username; ?>
else, display whatever you like.
Sorry Question is totally confusing ! You have said you are trying to pull data from dataBase but again in the code you are trying something from SESSION.
Make sure what you are doing is logically clear to you.
If you want to show user name then SESION will not help you. Also make sure user logged in and you have started session. If you are getting user data from database then you don't need session. Just check current user and then run query.
But all this is Php and MySQL related task not html.

Back to last page viewed on multi page site

Please forgive me if I'm over complicating this.
My goal: build an online course which allows the user to return to where they last stopped on a multi-page html/php site.
I purchased the aMember script, it's a php script that protects folders and files and allows membership levels. It does not come with any pre-made course pages or such, just a server side protection. It allows registration of user accounts and gives them access to specific folders and pages.
====
What I want to do is to build a sequential html5 course, with smaller chunks of info in each for easier learning. Building a menu to jump around is not ideal for this type of course. So I would want a button that takes a logged in user back to the page where they visited last time and to include it in the DB so that they can log in from anywhere and not count on cookies.
I am not a programmer so it's hard for me to explain in shorter terms, I hope you can understand and direct me to the right resources. Thanks!
Create a script that's included in every page of your site which will send info about user id,last visited page,time etc to database and your login script will redirect user accordingly from the information in your DB. Should not be that hard, if you need any code examples then ask.
You should store maybe user id in a session in login script.
For example the script for saving should be something like this:
if(isset($_SESSION['u_id'])){
$db_handler=mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die
('ERROR: Could not connect.');
$u_id = $_SESSION['u_id'];
$ref = $_SERVER['HTTP_REFERER'];
$query= "INSERT INTO user_activity(u_id,page) VALUES ($u_id, $ref);";
$res = mysqli_query($db_handler,$query);
if(!$res) {
die("ERROR: " . mysqli_error($db_handler));
}
}
And in your login script you should have something like this:
if(isset($_POST['user'])){
$db_handler=mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die
('ERROR: Could not connect.');
$u_id = $_POST['user'];
$query= "SELECT t.id,u.u_id,u.page from users t JOIN users_activity u ON t.id=u.u_id WHERE u.u_id=$u_id;";
$res = mysqli_query($db_handler,$query);
if(!$res) {
die("ERROR: " . mysqli_error($db_handler));
}
}
Should give you some idea, got busy at work so can't do better right now.

html button to reset field in mysql database using php

Kinda new to mysql and php
I have a hit counter for each page on my site and a private page that list all pages and hits.
I have a button that will reset all pages to zero and next to each page listing I have a reset button that will reset each page individually. This all was using a text file but now I am swtching to mysql database. I have coded the "RESET ALL" button to work but can not get the individual page buttons to work.
the processing code is:
if($_POST[ind_reset]) {
$ind_reset = $_POST[ind_reset];
mysql_connect("server", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql = 'UPDATE counters SET Hits =\'0\' WHERE Page = \'$ind_reset\';';
}
and the html form code is a string:
$page_reset = "<form id='Reset' action='counter_update.php' method='post'>
<button type='submit' name='ind_reset' value='$formPage'>RESET</button>
</form>";
Let's start with the first thing:
if($_POST[ind_reset]) {
should be
if($_POST['ind_reset']) {
It works without quotes because PHP is silently correcting your error. If you turned error reporting to E_ALL, you would get to see the error message.
One thing that you need to consider is that you can never trust POST data to be what you think it's supposed to be. Maybe you put in a typo. Maybe a hacker is sending you fake POST data. Whichever it is, it will mess up your code if the wrong thing gets put in that database update. For this reason, instead of simply plugging in that POST value into your database, you should have a checker to make sure that the value is a valid one. When I do things like this, I make an array of possible values and use only those values when updating or inserting into the database. Example:
$pages = array('value_on_page'=>'value_put_in_database',
'xyz'=>'thing_in_database_2');
//the valid things to post are either 'value_on_page' or 'xyz',
//but what goes into the database are the values those keys point to
//e.g. if $_POST['ind_reset'] == 'xyz', $ind_reset will be 'thing_in_database_2'
$key = $_POST['ind_reset'];
if(!isset($pages[$key])) {
//if that posted value isn't a key in the array, it's bad
error_log('Invalid posted page'.$key);
} else {
//this is a valid posted page
$ind_reset = $pages[$key];
//** do the database stuff right here in this spot **//
}
Now, for the reason your posted code doesn't work, you are missing the final, crucial part of doing a database query: the part where you actually run the query.
$conn = mysql_connect("server", "username", "password") or error_log(mysql_error());
mysql_select_db("database") or error_log(mysql_error());
$sql = 'UPDATE counters SET Hits =\'0\' WHERE Page = \'$ind_reset\';';
mysql_query($sql, $conn) or error_log(mysql_error());
I hope you have noted that I replaced "die" with "error_log." If you do error_log(mysql_error(), 1, 'youremail#example.com'), it will email it to you. Otherwise, as with in my examples, it gets put into wherever your system's error log file is. You can then have a nice history of your database errors so that, when you inevitably return to StackOverflow with more questions, you can tell us exactly what's been going on. If you use a file, just make sure to either rotate the error log file's name (I name them according to the day's date) or clear it out regularly, or it can get really, really long.
Using the mysqli code you posted in your comment is a better idea than the mysql_* functions, but you don't quite have it correct. The "bind_param" part sticks your variable into the spot where the question mark is. If your variable is a string, you put "s" first, or if it's an integer, you put "i" first, etc. And make sure you close things once you're done with them.
$db = new mysqli("server", "username", "password", "database");
if(!$db->connect_errno) {
$stmt = $db->prepare("UPDATE counters SET Hits = '0' where Page = ?");
$stmt->bind_param('s',$ind_reset); //assuming $ind_reset is a string
if(!$stmt->execute()) {
error_log($stmt->error);
}
$stmt->close();
} else {
error_log($db->connect_error);
}
$db->close();

Access table data when using PHP and MySQL

Okay, I can post the PHP code if needed but I'm trying to use some data in my database, but have no idea how I can access it. It might be an easy reply but I'm new to this game...
Basically, I have been able to set up a login system for my site, where if you log in, it will display the logged in user's username, this is done through the use of $_SESSION and a session class.
Where if the user is logged in ($session->logged_in) etc
<h3>Welcome <? echo $session->username?> </h3>
</head>
<body>
<p> Welcome to the website, your details are below </p>
</body>
<?php } ?>
I return the user's username as such.
However, I can only currently access data from the table 'users', and 'users' is connected through foreign keys to a table called 'passengers' through the 'username' field.
What I would like to do, is instead of printing the username, print the user's surname.
So essentially it is like:-
Logging in sets up a session and recognises the username that is logged in.
By querying this username in a different table, can pull up data from all corresponding tables in the database.
But I have no idea how to go about it..
If you guys and girls know of any sample code, or could point me in the right direction that'd be fantastic.
<? php
mysql_connect("localhost", "username", "password");
mysql_select_db("databasename");
$query = "SELECT surname FROM passengers WHERE username = " . $session->username . "";
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
echo "Hello, your lastname is $data";
?>
I think this is what you are referring to?
Also, even though you're new at php etc., try looking into mysql injection and how to prevent it (this current code is very susceptible to mysql injection -- if it were to use user input; thanks to Carrie Kendall lol =])
Good place to start is by using mysql_real_escape_string.
edit-
Not sure but this might also help out as I'm not entirely sure what you mean; mysql (left) join

Updating MySQL using SESSION variables via a jquery javascript function

I currently have a javascript file 'score.js' which makes use of jQuery.js, which is being called correctly via a link. The code in score.js is:
function originalUpdateScore(answer,correct){
if (answer == correct)
{
$.post('updateScore.php');
}
window.location.reload(true);
}
This function calls 'updateScore.php':
<?php
include("dbstuff.inc");
$con = mysqli_connect($host, $user, $passwd, $dbname)
or die ("Query died: connection");
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='$_SESSION[logname]')";
mysqli_query($con, $updateScore);
?>
However the database is not being updated correctly. If I replace the line:
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='$_SESSION[logname]')";
with:
$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
WHERE (user.Username='123pf')";
Where 123pf is the value that the SESSION variable contains in the php file calling the javascript it updates correctly. Why does using the session variable not work? Am I calling it incorrectly in the query?
Thanks in advance.
Are you calling session_start anywhere inside updateScore.php?
If you haven't started the session I do not believe that session variables will be available.
also, do you have complete control over $_SESSION['logname']? If not, someone could easily change their logname to inject SQL and damage/compromise your database. For example, if they were able to set their logname to be this, you could lose your user table:
$_SESSION['logname']="'; DROP TABLE user;-- ";
You're opening yourself right up to cheaters by playing like this. Under this scenario, any user could visit updateScore.php at any time to increase their stats, since that script neither checks their answer nor checks for a token that the JS builds to say the score is ok. It is a bad idea to keep this kind of logic on the front-end (javascript) without also having it verified on the back end (PHP); javascript & AJAX are very helpful shortcuts that can improve user experience, but they cannot be trusted as sole validity checkers.
It's probably just a transcription error, but the code that you have shown in your question uses $_SESSION[logname], it should be $_SESSION['logname'].

Categories