Display a row of the current session - php

So in my users table there are 5 columns. Id, username, password, email and money.
The money column is an int which is supposed to show how much money that user has. (I'm making a game).
I'm trying to make a script which displays how much money the user in the current session has, but my script displays the money for every user.
My code:
<?php session_start(); ?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['money'];
}
} else {
echo "You have no items yet!";
}
$conn->close();
?>
How would I do this?

You've missing where clause in your select query.
it would be something like:
$sql = "SELECT * FROM users WHERE id='{$_SESSION['user_id']}'";
$result = $conn->query($sql);
You just need to replace $_SESSION['user_id'] with the user id you are storing while user gets logged in.
EDIT:
Make sure you have session_start(); where page starts, additionally you may create unique index on email column in users table.
$sql = "SELECT * FROM users WHERE email='{$_SESSION['email']}'";
$result = $conn->query($sql);

Related

How to figure out if row is equal to a specific input

I am trying to figure out how to get a specific input from a database and fetching it. If its not equal to 1 do function.
Example code:
$admincheck = "SELECT admin FROM users";
if($admincheck == 0){
echo "<p style='font-size:40px;text-align:center;'><strong>Du har ikke tilgang til å se dette innholdet.</p>";
In my user database i have Username, Password, Admin.
Admin is default 0. If the number is 1 i want to grant access to that specific website.
You will need to connect to the database and then run your query. You will get a resultset back and you get the value you want from the resultset. Then you can do whatever you need to do with the result.
Try something like the following (most of this was pulled from: https://www.php.net/manual/en/mysqli.query.php):
$mysqli = new mysqli("localhost", "username", "password", "databasename");
$username = "whatever username you are checking";
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if ($result = $mysqli->query("select admin from users where username='$username'")) {
while($obj = $result->fetch_object()){
$is_admin = $obj->admin;
if ($is_admin === 0){
echo "whatever html you want to echo";
}
}
/* free result set */
$result->close();
}
$mysqli->close();
You will need to make sure that your database prevents more than one person from having the same username, I recommend adding a unique index on username. Usually people have an additional column called "id" that auto_increments so that it will always be a unique number and that's a lot easier to work with.
I recommend abstracting this logic into a separate file that will be responsible for verifying that the user is authenticated.
this query is not for one column
$admincheck = "SELECT admin FROM users";
you should add a where condition and after that, you can check if($admincheck == 0)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT admin FROM users where id=1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if($row->admin_check == 1){
/////this is your code to check admin...
}
}
} else {
echo "0 results";
}
$conn->close();
?>

Show records based on a catergory value

I have a table with data in it ID, Name, Task, Business. I am trying to show all records based on the Business category.
I would like a separate page to show all the businesses and then when you click on the name it displays all the records associated with it.
I am unsure of how to display this.
I can almost see what I want in SQL workbench but I am unsure how to do this is php code..
SELECT * FROM job2 where business="MR Plumber"
I want the "Mr plumber" to be what ever business I click on the business page.
I would like to have a page to list the businesses and then when I click on the business name link and displays all records associated to it.
Try this.
<?php $servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "error";
}
$sql = "your sql";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["column_name"];
}
} else {
echo "0 results";
}
$conn->close();
?>

Insert PhP & MySQL user data correctly

Forum residents!
I had a problem with a MySQL and PhP based user system: I want you to display only the data of the user with I am currently logged in.
The problem is that it also displays data from other users.
There is a MySQL table containing the following columns: id, username, password, email, VPSID. The goal is for each user to display their own VPSID, if the user logged in.
The site does not write anything or this display the data of all users.
The code:
<?php
session_start();
if(!isset($_SESSION['username'])){
header('location: login.php');
}
$hostname = 'blabla..';
$username = '';
$password = '';
$dbname = '';
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if(!$conn) {
echo "Connection error: " .mysqli_connect_error();
}
$result = mysqli_query($conn, "SELECT * FROM users WHERE id ='".$id."'");
while($row = mysqli_fetch_array($result)) {
echo $row['VPSID'];
}
?>
What have I done wrong and what is the right solution?
Thanks in advance!
$id is null thats your problem.
Maybe $id = $_SESSION["id"];
If you dont store it that way go off username since I'm going to guess they are unique
$user_name = $_SESSION["username"];
$result = mysqli_query($conn, "SELECT VPSID FROM users WHERE username ='$user_name'");
while($row = mysqli_fetch_array($result)) {
echo $row['VPSID'];
}

Trying to subtract amount from column in database, showing amount on all accounts

Objective:
I am trying to subtract 0.05 from a column in my database on the push of an html button.
What's going wrong:
Everything is working fine, it is making the correct calculation and deleting the correct amount from my account, but it is displaying the new amount on every account in the database.
Example:
I have 10 in my account, and once i press the button, i now have 9.95 in my account. Unfortunately, now everyone has 9.95 in their accounts too!
Code:
Html button and script for onclick:
<button id="playbutton" onclick="myAjax();location.href='5game.html'">Play (-5¢)</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'subtract5.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
PHP Code for subtracting 0.05 (file name: subtract5.php):
<?php
session_start();
$servername = "localhost";
$username = "my username"; <not actually this, just confidential
$password = "my password"; <not actually this, just confidential
$dbname = "accounts";
$cash_amount = $_SESSION['cash_amount'];
// Create connection
$userid = $_SESSION['id'];
// You must enter the user's id here. /\
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$newAmount = $cash_amount - 0.05;
$sql = "UPDATE users SET cash_amount = $newAmount";
$result = $conn->query($sql);
if($result)
{
echo "Query Executed Successfully!";
}
else
{
echo mysqli_error($conn);
}
$conn->close();
?>
Prediction:
I think this has something to do with the user id field, i wasn't sure what to put in it.
Database layout:
Database: Accounts,
Table: Users,
Columns: id | first_name | last_name | email | password | cash_amount | hash | active
Extra Question:
On the main page of my website, it shows the cash amount. Once it has been changed it does not update until i log out and log back in again. Is there a thing i can put in the top php code like "session restart" to check for new amounts every time i open the page?
Thanks:
Thanks so much for helping, as you can see i'm kind of a noob at this :)
In the where clause of the query WHERE id = $userid:
<?php
session_start();
$servername = "localhost";
$username = "my username"; <not actually this, just confidential
$password = "my password"; <not actually this, just confidential
$dbname = "accounts";
$cash_amount = $_SESSION['cash_amount'];
// Create connection
$userid = $_SESSION['id'];
// You must enter the user's id here. /\
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$newAmount = $cash_amount - 0.05;
$sql = "UPDATE users SET cash_amount = $newAmount WHERE id = $userid";
$result = $conn->query($sql);
if($result)
{
echo "Query Executed Successfully!";
}
else
{
echo mysqli_error($conn);
}
$conn->close();
?>
You need to limit the update to only one user using a WHERE clause
$sql = "UPDATE users SET cash_amount = $newAmount WHERE user_id = $userid LIMIT 1";
The LIMIT is added for security.

show results with same username php

I have a database which stores data. How can I view data in my database with the same username as my session? What I have tried is below. There is a session and the username is uploading in each row in the database.
This is what I'm trying to do: say I logged in as jack I typed data in and sent it to the database. It saves the name as jack and then only views the results with jack. But it is saying 0 results. Why?
<?php
session_start();
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
echo "$username";
}
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "score";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM all_scores WHERE username = '".$username."' ORDER BY id DESC LIMIT 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p></p>";
echo "". $row["name"]. "";
echo "<p>". $row["description"]. "</p>";
}
} else {
echo "0 results";
}
$conn->close();
?>
you have two mistakes
1- SQL syntax error, correct syntax is
$sql = "SELECT id, name, description FROM all_scores WHERE username = '".$username."'";
2- the variable $username is overwritten by the username of the database
try this:
$sql = "SELECT id, name, description FROM all_scores WHERE username = '".$_SESSION['username']."'";

Categories