PHP using session in a MYSQL query - php

I can echo the session name so i know its working but it doesn't work in a MySQL query. I even tried turning it into a variable and its still not working:
File list:
index.php
response.php
$repname = $_SESSION['name'];
$sql = "SELECT * FROM `employee` WHERE rep='".$repname."' ";
also
$sql = "SELECT * FROM `employee` WHERE rep=".$_SESSION['name']." ";
any ideas on what's wrong?
UPDATE**
Here's the right query
$sql = "SELECT * FROM `employee` WHERE rep='".$_SESSION['name']."' ";
I know its the right query because now i'm getting records to display but its only records where rep is blank. This means i'm not getting the session name for some reason.
I tried adding:
session_start();
if(isset($_GET['name'])){
$_SESSION['name']=$_GET['name'];
}
But im still only getting records where rep is blank

Be sure to add session_start() to the top of your session to initiate your session start
<?php
session_start(); ?>
Also be sure to add this to retrieve your name field:
<?php
session_start();
if(isset($_GET['name']){
$_SESSION['name']=$_GET['name'];
?>

Related

PHP database user selection

Alright, so I have setup a very simple login in and sign up database, it is working perfectly.
However, one of the page I have created where users can check their acccount information (Username and Email) is not working fully.
I have a database that has four columns ID, username, email and password.
All I am doing is taking the user information from the database (Who is logged in) and displaying their username and email on the page.
The problem is that the code is logging every user within the database, I only want it to select one user (The user that is logged in.)
Code:
<?php
// SQL query
$strSQL = "SELECT * FROM users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['email'] . "<br />";
echo $_SESSION['username'];
}
// Close the database connection
mysql_close();
?>
I'm thankful for the help !
You probably need to store the username value in a $_SESSION in your login session.
if (!isset($_SESSION)) {
session_start();
$_SESSION['id'] = the_id_of_your_logged_username;
}
Then using the value that is stored in the $_SESSION to retrieve the logged user.
session_start();
$id = $_SESSION['id'];
$query = "SELECT * FROM users WHERE id='$id'";
In these way, you can retrieve the logged user, just commonly on how users login and gets their profile directly.
Your SQL query should look something like this...
"SELECT * FROM users WHERE ID = '$user_id'"
Remember to fix any SQL vulnerabilities
$user_id = mysql_real_escape_string($user_id);

php mysql_query won't find index

I am creating a property profile page for a real estate site. For some reason it wont check the index in the database to see if it is the same value as the ?id= in the address bar. When I use the code select * from properties it doesn't show any error but when I add WHERE index='$prop_id' it kills the page and echo's query error. The database connection file is included at the top off the index.php page. Can anyone help?
<?php
if(isset($_GET['id'])){
$prop_id = mysql_real_escape_string($_GET['id'])or die("get error");
$check = mysql_query("SELECT * FROM properties WHERE index='$prop_id'") or die("query error");
}
?>
index is a reserved keyword. Fix the errors in the query. Missing ' -
"SELECT * FROM properties WHERE `index` = '$prop_id'"
Try as below :
"SELECT * FROM properties WHERE `index` = ".$prop_id;
You forgot one single quote in the query. Please replace your query with the following:
$check = mysql_query("SELECT * FROM properties WHERE index='".$prop_id."'") or die("query error");

How to give the users the ability to update their information

Hey guys I am new to programming and I have a quick question and hopefully it isnt too much. I am trying to give users of my test website to have the ability to update their information. I use the following code:
$mysqli = mysqli_connect('localhost', 'root', 'testpass', 'testdatabase')
or die(mysqli_error());
echo "<h2>How would you like to update your account $_SESSION[username]?</h2>";
$display = <<<END
<h4> Update your username here: <br/></h4>
<form method="POST" action="$_SERVER[PHP_SELF]">
<input type="text" name="update_username"/>
<input type="submit" name="submit" value="Update"/>
</form>
END;
echo $display;
$update_username = $_POST['update_username'];
$current_username = $_SESSION['username'];
$sql_update = "UPDATE users SET username = '$update_username' WHERE username = '$current_username'";
$result_update = mysqli_query($mysqli, $sql_update) or die (mysqli_error($mysqli));
The code above updates their information, but it only updates once. When I check the database after updating it, it changed to whatever I changed it too. Then I try and changed it again but it doesnt change, so I log out and log back in. When I log back in I change it, but this time, when I look at the database, there is no username. I log back out and log back in again. I change it again and it actually changes. I have to go through this same process everytime I try and change the username(or any other sort of information) and it gets very annoying. Do you guys have any ideas on why it is doing this?Thanks!
For database stuff, you want to track everything by IDs, so the first field in most every table will be 'id', set as primary key with auto increment. Then when updating you would do WHERE id = $userID. When they login, the user id would be stored in the session as well as username, and any queries would reference them by id. It also makes it a lot easier/faster to query/track stuff when you start doing table joins
try the following
END;
echo $display;
$update_username = $_POST['update_username'];
$current_username = $_SESSION['username'];
$current_id = mysql query select id where username = $current_username
$sql_update = "UPDATE users SET username = '$update_username' WHERE id = '$current_id'";
$result_update = mysqli_query($mysqli, $sql_update) or die (mysqli_error($mysqli));
hope you can fix my pseudo code in $current_id variable

Retrieving data from MySQL database using $_SESSION username

I am new at PHP and I'm trying to create a profile page whereby the user is able to view their information which they inserted when signing up to the website.
At first I'm attempting this with just their first name, so that whoever is logged in can see what first name they have saved on the database.
I have a included "checklog.php" page which includes
<? php session_start(); ?>;
And in my page, when i use;
echo $_SESSION['username']
The user's username is printed out fine.
So i've tried to apply this in mysqli query in order to print out their first name from the database like this;
<?php
if($db_server){
$query = "SELECT firstname FROM users WHERE username=$_SESSION['username']";
$result = mysqli_query($db_server, $query) or
die(mysql_error($db_server));
if (!$result) die('Query failed: ' . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
echo $row['firstname'];
}
}
mysqli_free_result($result);
?>
But I get an error on line 15 which is the SQL statement, can someone tell me what I'm doing wrong in my statement?
First of all add session_start(); in the top of the PHP code..
<?php
session_start();//<-- Here
Second.. rewrite your query like this..
$query = "SELECT firstname FROM users WHERE username= '".$_SESSION['username']."'";

How do I find out a specific row ID from a table?

Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);

Categories