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
Related
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.
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.
I have the following code which is supposed to insert a row into a DB table "clicks" (consisting 1 Primary AI column "id" and another column "user" which contains the user's sessions id) upon clicking the Like button. For each user assuming they have a session id set from a login I would like to return to them their most recently inserted id from the table. So the first time the button is clicked it will return 1 etc.
I would like this to be accessible to multiple users through a login system. I was wondering if there are any major security vulnerabilities with my code e.g can the results be forged etc?
index.php:
<?php
include 'init.php';
include 'connect.php';
?>
<!doctype html>
<html>
<body>
<?php
$userid = $_SESSION['user_id'];
echo '<a class="like" href="#" onclick="like_add(', $userid,
');">Like</a>';
?>
<script type ="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type ="text/javascript" src="like.js"></script>
</body>
</html>
connect.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "DB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
init.php:
<?php
session_start();
$_SESSION['user_id']='1';
$userid = $_SESSION['user_id'];
include 'connect.php';
include 'like.php';
?>
like.js:
function like_add(userid) {
$.post('like_add.php', {userid:userid}, function(data) {
if (data == 'success'){
add_like($userid);
} else{
alert(data);
}
});
}
like.php:
<?php
function add_like($userid){
include 'connect.php';
$stmt = $conn->prepare("INSERT INTO clicks (user) VALUES (?)");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt = $conn->prepare("SELECT max(id) FROM clicks WHERE user=?");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($click);
$stmt->fetch();
echo $click;
$stmt->close();
}
?>
like_add.php:
<?php
include 'init.php';
if (isset($userid)) {
$userid = $userid;
add_like($userid);
}
?>
Your query might give incorrect results if the same user sends multiple requests almost at the same time, case when your query will not return the currently inserted id. You can use the last_insert_id() mysql function which gives you the last inserted auto-increment value, regardless if meanwhile other requests updated the table.
Also, you don't need to pass the user_id parameter with the ajax request, as you anyway can obtain it from the session. Passing the user_id can be considered a security hole, as anyone can modify the onclick handler and trigger clicks for other users. I'd recommend avoiding as much as possible sending user ids in plain text as response.
To add more security: in your connection script. Change the $servername, $username etc to constants. These don’t need to change, and you don’t want them to be changed.
Do you have any type of checks for your sessions? Sessions are more secure than cookies but they can be hijacked in transit when a user logs in. To add some security to your session, use the session_regenerate_id() function when the user logs in, this will generate a new session id therefore if the users id has been hijacked, it is of no use as it will have changed. There are other checks that can be carried out on sessions to secure them but this is a good quick way of adding an extra level.
#nomistic makes some good suggestions also especially regarding encryption of passwords and other sensitive information. Using the crypt() function or PHP’s password hashing API - http://php.net/manual/en/book.password.php. Is also a good way.
This looks pretty good on the php side. You are using session ids for user verification, and have prepared your SQL inserts. (One question, why are you setting $_SESSION['user_id']='1'? Do you plan on only having one user? That doesn't seem necessary to me)
However, you might want to tighten up your database-side security. It's probably a good idea to set up a different user for public database access, and limit the actions on the database side. For instance, if all they are going to do is select or insert, that user should only have access to do so. I wouldn't use your root account for that. Though it's probably not a huge risk (you are doing pretty well against SQL injection, at least the first two times) just to add another layer is always a good idea.
When dealing with security, it's helpful to think of a "use-case" scenario. What sort of data are you storing? Is it something that somebody really would want? (e.g. is it financial?) It's always a good idea to look at the human element. Would someone want to spend more than a day trying to hack your data (is it worth it for them?).
Also, though it's not evident here, you probably want to make sure you have a good form of encrypting passwords.
Another thought: even if it is minor risk, it's not a bad idea to run daily backups, so you can recover your data in a worst-case scenario.
Edit:
Since it was asked, here's how to setup security at the database side:
First create a new user (following this pattern):
CREATE USER 'newuser'#'localhost' IDENTIFIED BY 'password';
Granting permissions work like this:
GRANT [type of permission] ON [database name].[table name] TO ‘[username]’#'localhost’;
Types of privileges include ALL PRIVILEGES, CREATE,DROP, DELETE, INSERT, SELECT, UPDATE, GRANT OPTION.
If you want to read up on this more, here's the documentation: https://dev.mysql.com/doc/refman/5.1/en/adding-users.html
I have been programming for a while but pretty new to PHP. I am have run into a problem. My site has a login/register screen and once logged into the account, I am trying to echo information from the users database entry. For example if I want to display the content "Balance" I have been trying the following code:
<?php
$data = mysql_query("SELECT * FROM users WHERE username=username") or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print $info['balance'];
}
?>
The idea is that the script will query the database using the username stored in the session then goto the named field.
When there is only one registered user, it appears to work, however; once multiple users enroll, it echoes the value from ALL users (ex. $7.50$10.12).
Thanks for your help in resolving this issue!
Currently you are not comparing the username to a variable, but you are comparing it to itself, which means it will always be true.
<?
$username = $_SESSION['username'];//or other methods like $_POST['username'] or $_GET['username'], depending on how you intend to get the username;
$data = mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{ Print $info['balance']; }
?>
You neet to make sure the $username is escaped (if comes from user input) as well as start using mysqli or pdo instead of mysql.
And, of course, I'm assuming you are using session_start() somewhere and actually assigning the username to the session.
Hope this helps!
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.