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.
Related
I will try to keep this post as simple as possible while including as much information as I can to assist you in helping me. Just as a forewarning, I am extremely new to PHP/Mysqli and over the course of the last week put together an internal data site for our company to make our jobs easier.
I have completed the user login process and it seems to be working quite well. If the user is not logged in, they can not see the PHP pages of the site and are redirected accordingly. Now that I have this part working. I am trying to incorporate a site identifier that shows their first and last name as well as a photo of them. The placeholders are already setup but I have not been very successful in getting this to work. I did, however, add a "Welcome "Email" message at the time by pulling the session data.
I will list the code that I am currently using below:
LOGIN PAGE:
<?php
require('../inc/db.inc.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['user_email'])){
$email = stripslashes($_REQUEST['user_email']); // removes backslashes
$email = mysqli_real_escape_string($con,$email); //escapes special characters in a string
$password = stripslashes($_REQUEST['user_pwd']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE user_email='$email' and user_pwd='".md5($password)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['user_email'] = $email;
header("Location: ../index.php"); // Redirect user to index.php
}else{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
DB PAGE:
<?php
$con = mysqli_connect("localhost","root","","dbadmin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
SECURITY ON EACH PAGE:
<?php
include("pages/auth.php"); //include auth.php file on all secure pages
?>
AUTH PAGE:
<?php
session_start();
if(!isset($_SESSION["user_email"])){
header("Location: login.php");
exit(); }
?>
CODE USED TO DISPLAY EMAIL: ( only code I was able to get working)
<p>Welcome <?php echo $_SESSION['user_email']; ?>
I hope that one of you Guru types see that and know exactly how to get what I am looking for, or at least point me in the right direction. I have been searching the internet fir what seems like days reading all of the tutorials that I can find but I have not been able to successfully make anything work. I have found the following code but each time I try to add it to my code, it breaks the site.
$row = mysql_fetch_array($result);
Please assist if you are able. Thanks in advance.
Go to your login page where you check if row is equal 1, do this, change this
$_SESSION['user_email'] = $email;
To this
$_SESSION['user'] = $result->fetch_assoc();
Then do this
<p>Welcome <?php echo $_SESSION['user']['firstname']; ?></p>
Not a direct answer to your questions, but if are new to php, I would advise you to use one of the popular framework of php that already provide what you are looking for, and more, in a secure way, with secured libraries.
for example laravel or symfony.
Those are very well documented, and you will learn much more checking their documentation and tutorial than trying to reinvent the wheel here.
I have created and app with a working login and registration. When someone logs in and presses a button there username is sent to a Earn.php file that is connected to my database that has a points column in it. My problem lies with adding, lets say 5 points to the users specific account.
Example: Username sent to php file from app> then the php file takes that specific username and add 5 points to its point column in the database. Like 5+5=10
What I have now:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = $_POST["username"];
?>
Sorry if this is a lot to ask for, I very knew at this! Any help is very much appreciated, thanks!
This has a simple solution. You can use update statement:
$q = "UPDATE TableName SET points = points + 5 WHERE username_column ='".$username."'";
$r = mysqli_query($con , $q) or die();
Let me know if there is anything else.
So I managed to fix it myself, unsure how tho, this is my final code:
//create user
$con=mysqli_connect("localhost","root","******");
$crearuser="CREATE USER 'phpuser'#'localhost' identified by '******'";
if (mysqli_query($con,$sql))
{
echo "It Works";
}
else
{
echo "Nope";
}
Like I said, im unsure of how I fixed it, but this and the grant part (not going to paste, so much code) are fully working, thank you all :)
Just reference to it: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html
$createuser = "CREATE USER 'phpuser'#'localhost' IDENTIFIED BY 'some_pass';";
Your Script runs fine on my side. I think you have problem in connecting with database
$con = mysqli_connect("localhost","root","******","mysql");
Because during the editing process you changed your password parameter 3 times. And you are not sure about your password.
Try to figure out your mysqli_connect() parameters.
This question will help you too..How to find out the username and password for mysql database
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.
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