How to get session variable from 2 different tables? - php

I am new in PHP. I use session first time. I have two tables in db. First table with name pacra_teams with column id and title. Second table is og_users with multiple column but i use team_title as foreign key as store id against team title.
Now i want to create a session and want to display team name from table pacra_teams and user name from table og_users.
I try following code but i failed.
<?php
// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
// setting variable values during session
$_SESSION['og_users.username']=$username;
$_SESSION['pacra_teams.title']=$title;
?>
call these variables
<?php
session_start();
?>
<?php
print_r($_SESSION);
?>
Please help me how i can do this?
One Thing More. if i run seesion.php page it display undefine variable "title"
and if i run print code. It display username "root" but i dont have any user name root in my db

You already defined a query but didn't execute it.
// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
$result = $conn->query($sql);
$row = $result->fetch_object();
// setting variable values during session
$_SESSION['og_users.username'] = $row->USER_NAME; // Change to correct column name in table og_users
$_SESSION['pacra_teams.title'] = $row->TITLE_COLUMN_NAME; // Change to correct column name in table pacra_teams

The result will be the same every time without a WHERE clause in your sql statement. It's only going to return the first row it finds. It looks like you're trying to set user information in a session variable so you can call the data throughout your application so here's a possible solution assuming you grab an ID for the user somewhere (IE web form).
This is a simple answer to explain a concept, not a tutorial.
<?php
//Setup your connection stuff here
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
//Get a user's name from a form
$userName = $_POST['username'];
// Perform your query
$db= new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
WHERE og_users.username = {$userName} LIMIT 1";
if(!$result = $db->query($sql)){
die('Error [' . $db->error . ']');
}
// Setting variable values during session
while($row = $result->fetch_assoc()) {
$_SESSION['ogUsername'] = $row['USERNAME']; // USERNAME is a placeholder for the example
$_SESSION['pacraTeamsTitle'] = $row['TITLE']; // Same here
}
It's not perfect, but hopefully it helps explain the concept and helps you complete your task.

Related

Can someone explain PHP SQL Select data to me?

I want to select the password data of a user so they can log in on my website (for a member only website). I have a hash of the password and the username written to a table called "users" upon account creation. I do not know how to select a row on the table, so I get the error when the code looks for, something?
I found this on w3, but I don't understand what each part of the code means.
I tried to edit the code so it would match my user case, but I don't know how to.
$servername ="127.0.0.1";
$dbusername = "root";
$dbpassword = "";
$dbname = "users";
//create connection to db
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
$sql = "SELECT id, username, password FROM users";
$result == $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row == $result->fetch_assoc()) {
echo $userid = $row["id"] && $serverpassword = $row["password"] && $serverusername = $row["username"];
}
} else {
echo "User Lookup Failed";
}
$conn->close();
You don't need to select all records from database and then iterate all of them to check correct user. Besides, you should only select user by username and password as below:
$sql = "SELECT id, username, password FROM users WHERE username = '".$serverusername."' AND `password` = '".serverpassword."' ";
Apart, you should use data binding instead of variable to avoid SQL injection.

how to include a php variable as part of a table name?

I have a site where I needed to use separate table names for each of my clients because the data has to be updated all the time with a manual import.
example:
kansas_users
newyork_users
I have set a global variable as $client which will create the state name on all pages so if I echo "$client"; then I will see "kansas" for example on any page.
I would like to include this variable as part of my SQL query if possible to make it easier to code:
SELECT "nick, firstname, lastname, cell
FROM database.$client_members
where active =1 and id = $user->id";
Is this possible or even safe to do?
Yes it possible you can do some thing like below
<?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);
}
$client = 'kansas';
$table_name = "database." . $conn->real_escape_string($client) . "_members";
$query = sprintf("SELECT nick, firstname, lastname, cell
FROM %s WHERE active = 1 and id = ?", $table_name);
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user->id);
But i think you should seriously consider normalizing your database to avoid such issues

Query records belonging to the logged in user

I've written the below query:
At the moment this pulls back everything from the MarketingCampaigns table, regardless of which user created the record.
I need to be able to return the result, which counts only the records created by that user.
<?php
$servername = "localhost";
$username = "root";
$password = "doimkr943k3f";
$dbname = "crm4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT format(count(id),0) as id12 FROM MarketingCampaigns";
$result2 = $conn->query($sql);
$row = $result2->fetch_assoc();
echo $row["id12"];
?>
The below is a query I can see has been 'auto-generated' by the tool I use, which checks which fields the user should see in table view. I'm just really unsure how to convert this into the simple, single value SQL queries I have above.
// mm: build the query based on current member's permissions
$DisplayRecords = $_REQUEST['DisplayRecords'];
if(!in_array($DisplayRecords, array('user', 'group'))){ $DisplayRecords = 'all'; }
if($perm[2]==1 || ($perm[2]>1 && $DisplayRecords=='user' && !$_REQUEST['NoFilter_x'])){ // view owner only
$x->QueryFrom.=', membership_userrecords';
$x->QueryWhere="where `Complaints`.`id`=membership_userrecords.pkValue and membership_userrecords.tableName='Complaints' and lcase(membership_userrecords.memberID)='".getLoggedMemberID()."'";
}elseif($perm[2]==2 || ($perm[2]>2 && $DisplayRecords=='group' && !$_REQUEST['NoFilter_x'])){ // view group only
$x->QueryFrom.=', membership_userrecords';
$x->QueryWhere="where `Complaints`.`id`=membership_userrecords.pkValue and membership_userrecords.tableName='Complaints' and membership_userrecords.groupID='".getLoggedGroupID()."'";
}elseif($perm[2]==3){ // view all
// no further action
}elseif($perm[2]==0){ // view none
$x->QueryFields = array("Not enough permissions" => "NEP");
$x->QueryFrom = '`Complaints`';
$x->QueryWhere = '';
$x->DefaultSortField = '';
}
I have a table called membership_userrecords which includes the below fields.
You can see the PK value in the table and which user owns it.
I'm just not sure how to do the SQL query.
Can you help?
EDIT: I really need to work on my PHP syntax lol. Thanks #aynber
Assuming the username and the memberID are the same, this should be your query.
$sql= $conn->prepare("SELECT format(count(*),0) as id12 FROM MarketingCampaigns where memberID = ?");
$sql->bind_param("s", $username);
$sql->execute();
$sql->bind_result($row);
$sql->fetch();
echo $row;
I'm really unsure about your data here.

Assign row values from SQL to php variables from URL query

I have a SQL table, a php page. Both set up on a website using cPanel hosting.
The SQL table is like this. Table name is "dbase".
It has two columns, id and name and each column has two rows, say.
Id -> 01, 02
Name -> Name1, Name2.
What I want to do is.
If my page URL is examp.le/page.php?id=01 , or something like that which has a parameter 'id' valued as 01.
How do I assign value for php variable in that page say, $name as the corresponding value for 'name' column in the '01' row?
You have to get the parameter form the url using $_GET[] and then you have to query from the table to get the Name.
Just try this. Hope it helps you.
$id = $_GET['id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM dbase where Id=".$id;
$result = $conn->query($sql);
$name;
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
$name = $row['Name'];
} else {
echo "0 results";
}
Now just access $name wherever you want

PHP Select fields from database where username equals X

im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.

Categories