How to select data from a specific user using INNER JOIN - php

I want to select data from a specific user. When he is logged in on the website he will see information related to him.
I'm using INNER JOIN and I need to select data related to his login or id.
Any account that I use to login, I can access all exercises registered =/
On this case I'm using an ID.
Is something wrong with the query?
I don't get any errors from PHP. Where can I put the WHERE clause?
Code:
<?php
$login = $_SESSION['login'];
$consulta = mysqli_query($conexao,"SELECT exercicios.nome_exercicio AS nome_exc,
exercicios.repeticoes_exercicio AS rep_exc,
exercicios.serie_exercicio AS serie_exc
FROM exercicios
INNER JOIN usuarios ON usuarios.id_usuario = exercicios.id_usuario WHERE exercicios.id_usuario = '5'");
if(mysqli_num_rows($consulta)> 0){
echo "<div class='table-responsive'><table class='table table-responsive'>
<tr><td>Nome</td><td>Repetições</td><td>Série</td></tr>";
while ($exercicio = mysqli_fetch_assoc($consulta))
{
print"<tr>
<td>$exercicio[nome_exc]</td>
<td>$exercicio[rep_exc]</td>
<td>$exercicio[serie_exc]</td>
</tr>";
}
echo " </table></div>";
}
else {
echo "<h3>Seu instrutor ainda não cadastrou exercícios</h3>";
}
?>

You are missed some important things, for example, what data are you storing in your session variable login?
$login = $_SESSION['login'];
When a user send the login data first time (for example email and password), you will search the data on the database (table accounts or users or the table you need) and then if exist you should store the user data on session (the id is the most important). So, when you need to access to the exercises of the user, you need only to specify the correct user id on the where condition like ($login in this example is an array with user data):
"SELECT .... FROM .... WHERE id = {$login['userId']}"
Hope this explanation will be enough to fix your problem.

Related

Create Custom Wordpress Login Credentials Programmatically

I am have a membership directory for physicians using gravity forms for the registration page and gravity view to display the members in the directory..
The site owner informed me after-the-fact that the login credentials are to be set to specific unique criteria that are specific to each member..
For example the username is to be that individuals members license number and the password is to be the last name of the member..
Is there a way to run a script that will automatically update all of the usernames and passwords for the existing members? Keep in mind that there are over 900 active members in this directory. Or am I going to have to manually update all of the usernames and passwords in the database?
You will need to create a script in SSMS then to update all the username and password pairs. Maybe something like this:
update dbo.Users
set Password = LastName,UserName = LicenseNumber
from dbo.User
where LastName is not null and LicenseNumber is not null
Obviously, I cannot test this as I don't know the structure of your DB or the names of the tables involved. If there are more than one table and you have to join them it could look like this:
update dbo.UserData
set UD.Password = U.LastNamen UD.UserName = U.LicenseNumber
from dbo.UserData UD
LEFT JOIN dbo.User U on U.Id = UD.UserID
where U.LicenseNumber is not null and U.LastName is not null
I am using the not null for both the LicenseNumber and LastName since the user will need both to have a username and password set by this script.
If you provide more information I could give a more specific answer.
Try using the wp_create_user function:
<?php
// make an array of all the users you want to add
$allusers = array();
$allusers[0]['username'] = 'sally_sparrow';
$allusers[0]['email'] = 'sally#example.com';
$allusers[0]['password'] = '26aWpfRFcNhcZjBLLj3d';
$allusers[1]['username'] = 'sam_smith';
$allusers[1]['email'] = 'sam#example.com';
$allusers[1]['password'] = '9VF4qTXLhTJdCWzbbL9s';
// etc...
foreach ($allusers as $user) {
$result = wp_create_user( $user['username'], $user['password'], $user['email'] );
if ( is_wp_error( $result ) ) {
echo '<div class="error notice">' . $return->get_error_message() . '</div>';
}
else {
echo '<div class="updated notice">Added user id #' . $result . '</div>';
}
}
?>

Using sessions to display the profile of a logged in user from a database with PHP

I have been having an issue selecting data from my database based on the user id column. I know that I have to make use of PHP sessions to enable each user see their profile when they login, but I haven't been able to work out the code for this.
Here is what I have so far:
<?php session_start(); include 'dpconfig.php'; $id = $_SESSION['uid'] ?>
<?php
$run = mysqli_query($conn,"Select * from user Where first = '$id'");
$row = mysqli_fetch_array($run, MYSQLI_BOTH); {}
$showid = $row[0];
$showfirst = $row[1];
$showlast = $row[2];
echo $showid;
echo $showfirst;
echo $showlast;
?>
If I run the above code I get nothing echoed out, but if I remove the WHERE clause from my SELECT statement, all logged in users see the first column of my database.
I want each user to see their own profile, I learnt that I need to authenticate session, and I am confused. Please help.
Assumptions
I'm assuming your database has three columns, uid (the id of a user, int, primary key, auto_increment), first (the user's first name, varchar) and last (the user's last name, varchar).
I'm also assuming that when the user logs in, $_SESSION["UID"] is set to the value of the id column in their row.
Solution
As far as I can see, your WHERE clause is wrong. You wrote
Select * from user Where first = '$id'
which essentially means "Select everything from the user table where the first name is equal to the currently logged in user's id". I think you meant something more like
SELECT first, last FROM user WHERE uid='$id'
which means "Select the first and last names from the user table where the id is equal to the currently logged in user's id".
Code
I have re-written your PHP file, to make it a bit more readable and clear. You'll need to change the MySQL connection to whatever you were originally using, but apart from that, everything should work fine.
<?php
session_start();
require("dpconfig.php");
$q = "SELECT first, last FROM user WHERE uid='".$_SESSION["UID"]."'";
$r = mysqli_query($conn,$q);
$a = mysqli_fetch_assoc($r);
echo "First Name: ".$a["first"]."<br>";
echo "Last Name:".$a["last"];
?>
Second Question
For your form:
<form method="post" action="update.php">
<input type="text" name="status"><br>
<button>Submit</button>
</form>
For update.php:
<?php
session_start();
require("dpconfig.php");
if (isset($_POST["status"])) {
$q = "UPDATE user SET status='".addslashes($_POST["status"])."' WHERE uid='".$_SESSION["uid"]."'";
mysqli_query($conn,$q);
}
header("Location:./");
?>

PHP get variable from on table and then use that variable to select from a second table

I'm building a followers list for a user. I have two tables the first shows the relationships between users and the second table holds every users profile info. In the following code, I first select from the user relationships table to get a variable {$userid1} which is the value of all the user ids that follow the current user. When I echo out {$userid1} I get all the ids of the users who follow the current user but it is one giant connected string. I want to take the variable {$userid1} and use it to pull every one of those follower's user data from the profile table. I want every user's data to show up from the profile table that follows the current user. The code works however only the newest follower's profile data is pulled from the profile table. I was thinking putting the variable {$userid1} into an array and using foreach, but I'm not sure how the syntax would be. Anybody know how it could work? The problem is a variable can only hold one value at a time.
Output of the first query are the iduser numbers from the users following the current user.
e.g. when echoed echo $userid1 . " "; the results are the ids look like this: 45 56 67
I added a space between numbers in the echo statement.
$sql = mysql_query("SELECT * FROM followrelations Where iduser2='$uid' "); //followers from relations table
while($row = mysql_fetch_array($sql)){
$userid1 = $row['iduser1'];
echo $userid1 . " ";
}
$sql = mysql_query("SELECT * FROM profile where iduser=$userid1 ORDER BY username ");//get followers infor from profile using variable
while($row = mysql_fetch_array($sql)){
$iduserf = $row['iduser']; //userid2 requires different var name so program does not get mixed up
$username = $row['username'];
$bio = $row['bio'];
$avatar = $row['avatar'];
echo "
<div style='width:500px;height:100px;padding:20px 20px;float:left;border: solid black 1px;'>
<a href='profile.php?uid=$iduserf'><img src=$avatar height=50px width=50px /></a></br>
<a href='profile.php?uid=$iduserf'>$username </a></br>
</div>" ;
}
You might be looking for subqueries:
SELECT username
FROM user_table
WHERE id IN( SELECT user_id WHERE linked_user_id = 123 )
This is simplefied to be a better example. This will select the username of all users from the user_table, where the ID exist in the subquery.
In turn, the subquery selects all user_id where the linked user has id=123.
The subquery is quite similar to making an array in PHP and use that info for the next query.
Small note: Be carefull with subqueries. They're perfect in my example above, but eg not all servers support a limit in the subquery. This might effect performance. The more complecated functions don't work in a subquery. Try to keep those simple.
You can use something like the following to execute this in a single query:
$id = mysql_real_escape_string($uid);
$sql = <<<SQL
SELECT
p.*
FROM profile as p
INNER JOIN followrelations as fl
ON fl.iduser1 = p.userid
WHERE fl.iduser2 = $id
ORDER BY username
SQL;
$stmt = mysql_query($sql);
while($row = mysql_fetch_array($stmt)){
// Rest of the logic here
}
This will return all the fields in your profile table. Note that the mysql_ extension is deprecated and unsafe - you should not be using it in new code. Take a look at How to replace MySQL functions with PDO? and How can I prevent SQL injection in PHP? for some good practices regarding this.
Found my mistake, the second $sql should be another name (I named it $sql1), and the second half should all be within the first while.
$sql = mysql_query("SELECT * FROM followrelations Where iduser2='$uid' "); //followers session uid
while($row = mysql_fetch_array($sql)){
$userid1 = $row['iduser1'];
$sql1 = mysql_query("SELECT * FROM profile where iduser='$userid1' ORDER BY username ");//get followers infor from profile using variable
while($row = mysql_fetch_array($sql1)){
$iduserf = $row['iduser']; //userid2 requires different var name so program does not get mixed up
$username = $row['username'];
$bio = $row['bio'];
$avatar = $row['avatar'];
echo "
<div style='width:500px;height:100px;padding:20px 20px;float:left;border: solid black 1px;'>
<a href='profile.php?uid=$iduserf'><img src=$avatar height=50px width=50px /></a></br>
<a href='profile.php?uid=$iduserf'>$username </a></br>
</div>" ;
}
}

Select user if the user has data on another table

Good Afternoon.
I am trying to create a list of all the Users in my database that contain data in a certain table.
I have 2 tables.
USERS - Contains the name of all the users
DATA - Contains data relative to the user (IT isn't called DATA obviously).
Let's say i have 3 users:
Pedro;
Armando;
Henrique;
Pedro has data in the second table. "Armando" and "Henrique" Don't have any data in the other table.
I want to print the name of all users that contain data on the "data" table.
I tried to do this:
$query=mysql_query("select nome from users where nome <> 'admin' ORDER BY nome");
while ($whatever=mysql_fetch_array($query, MYSQL_ASSOC)){
foreach ($whatever as $w){
echo $w. ' '; //$w contains the name of all the users.
$queryy = mysql_query("select id from users where nome='$w'");
$idd = mysql_fetch_array($queryy);
}
}
$conta=count($idd);
for ($i=0;$i<$conta;$i++){
echo $idd[$i];
$queryyy=mysql_query("select * from pp where id_user='$idd[$i]'");
}
On the table "pp", the field is id_user, as it is stated there, instead of "id" like on the users table.
I don't know how to proceed from here on out, since i am new to php.
Thanks
A simple JOIN can get this for you -
SELECT USERS.name
FROM USERS
JOIN DATA
ON USERS.name = DATA.name

MySQL INNER JOIN using an OR whilst logging in

My table structure is as follows:
~ MEMBERS ~
UID (a-i)
NAME
EMAIL
~ COUPLES ~
UID_1
UID_2
PASSWORD
SALT
When a couple sign up, their UIDs get inserted in to the couples table, along with their joint password (and its salt). Now, when logging in, I need to join the tables so I can check the password for either user.
i.e. Find Email Address > See which Couple they are in > Check against Password
This is my current query:
$query = "SELECT * FROM MEMBERS m
INNER JOIN COUPLES c ON ((c.UID_1 = m.UID) OR (c.UID_2 = m.UID))
WHERE EMAIL = '$email'";
(I'm only using * for now as I can't figure out exactly what I need to select for the INNER JOIN to work.)
And the rest of the code on login-script.php is as follows:
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0) {
header('Location: index.php?msg=error4');
exit();
}
$data = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $data['SALT'] . hash('sha256', $password));
if ($hash != $data['PASSWORD']) {
header('Location: index.php?msg=error5');
exit();
}
else {
echo "Logged in.";
}
?>
If I try and log in, the error message ?msg=error5 gets thrown, which means that the passwords do not match, but I cannot see a problem in that part of my code. I believe it's telling me they do not match because it's not looking in the right table/for the right data, which must be something wrong with my INNER JOIN.
Any help would be much appreciated.
EDIT: I realise now that it would have made a lot more sense to have just put the password and salt in to MEMBERS for both records so I'm only selecting from one table, but the deed is done and I'm curious to see if this is possible.
Actually, I tried your structure and code on http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all and this works for me:
SELECT * from members M JOIN couples C ON uid_1=Uid or uid_2=uid
WHERE email='youremail';
Perhaps the problem is that in the table there is more than 1 couple a person is actually in?
Like:
uid_1, uid_2, pass
1 2 xxx
1 3 yyy
You should either limit it on database side to unique columns or change code, because if you don't, you might be getting more than 1 row as result and you would need to check every couple's password against particular UID.

Categories