Get friends profile picture(s) from user table - php

I have 2 table's:
Users (id, username, email, avatar, etc...);
Friends (id, user1, user2, status);
Now I want to build on my profile page an list of my friends with there avatar(s). I'm trying for like 4 hours by myself but i don't get it... :(
BTW: this is an error i got!
Notice: Array to string conversion in /home/reduaqi158/domains/reduankurtaj.eu/public_html/snapfriends/vrienden.php on line 26
This is what i have right now:
<?php
error_reporting(E_ALL);
session_start();
$username = $_SESSION['username'];
$status = 2;
include "includes/conn.php";
$vrienden=mysqli_query($server,"SELECT * FROM vrienden WHERE status='$status' && vriend1='$username' || vriend2='$username' ");
$vriend_list = array();
while($row = mysqli_fetch_array($vrienden))
{
if ($row['vriend1'] == $username) {
$vriend_list[] = $row['vriend2'];
}
else {
$vriend_list[] = $row['vriend1'];
}
}
echo json_encode($vriend_list);
$foto=mysqli_query($server,"SELECT prof_pic FROM users WHERE username='$vriend_list['vriend1''vriend2']' ");
while($row2 = mysqli_fetch_array($foto)) {
echo "<img class='img-rounded' src=assets/profiel/".$row2['prof_pic']." alt='Card image cap'>";
}
?>
json_encode output:
["ja","amando"]
Someone who can help me pls :)

Your initial approach is very confusing.
Almost everything in your code can be substituted by single SQL query.
You can use JOIN to get all your friends with their avatars in one go:
SELECT u.username as username, u.avatar as avatar,.... <== all columns which you need
FROM `friends_table` f <== your friends table
JOIN `users_table` u <== your users table
ON (f.user1 = u.id) <== notice that i join on user1 column
WHERE u.username = '$username' && f.status = '$status'
UNION
SELECT u.username as username, u.avatar as avatar,.... <== same columns
FROM `friends_table` f <== your friends table
JOIN `users_table` u <== your users table
ON (f.user2 = u.id) <== notice that i join on user2 column
WHERE u.username = '$username' && f.status = '$status'
By this query you select all users who are in a friendship with your $username. You need union because you don't know in which field (user1 or user2) your $username is located.
NOTE: I strongly suggest using prepared statements instead of just putting '$var' inside SQL query to prevent SQL Injection.
After executing this query you can parse results and display avatars in such a way:
while($row = mysqli_fetch_array($vrienden, MYSQLI_ASSOC))
{
echo "<img class='img-rounded' src=assets/profiel/".$row['avatar']." alt='Card image cap'>";
}
I hope you got the idea.

in your while statement you have to declare a value for the array. like array[0] = value. so that you know that array position 0 has a certain value. Like what I did here below. Don't know if it's in PHP like this but certain in .net you have to declare the location of a value in an array.
while($row = mysqli_fetch_array($vrienden))
{
if ($row['vriend1'] == $username) {
$vriend_list[0] = $row['vriend2'];
}
else {
$vriend_list[1] = $row['vriend1'];
}
}
and the following
$foto=mysqli_query($server,"SELECT prof_pic FROM users WHERE username='$vriend_list['vriend1''vriend2']' ");
shouldn't it be $vriend_list['vriend1'] . $vriend_list['vriend2']'
you have to use a connect character (the . in PHP)

Related

Showing two different values depending on SESSION value in INNER JOIN

I have two different tables, one named users, and another named transactions. Transactions contains wallet1, wallet2, amount. Users contains user details such as firstname, lastname, and wallet. I am trying to display the corresponding first name and last name, depending on whether or not the SESSION_wallet is equal to wallet1 or wallet2 within transactions. I tried searching for a while, and came up with a solution for showing the correct display name for the first and last name making the transfer, however, I am trying to make it display the correct value for "Transfer to:"
Here is some of my code to get a better understanding of what I mean:
MySQLi Query:
$result2 = mysqli_query($link, "SELECT * FROM transactions INNER JOIN users ON transactions.wallet1 = users.wallet WHERE transactions.wallet1 = '" . $_SESSION["wallet"] . "' OR transactions.wallet2 = '" . $_SESSION["wallet"] . "' Order by transactions.id DESC LIMIT 5 ");
PHP Code:
<?php
if(mysqli_num_rows($result2) > 0)
{
while($row = mysqli_fetch_array($result2))
{
?>
The table that needs to display the transfer from, and transfer to:
<?php
if ($_SESSION["wallet"] == $row["wallet1"]) {
echo "<td>Transfer to ".$row["firstname"]." ".$row["lastname"]."</td>";
}
else if ($_SESSION["wallet"] == $row["wallet2"]) {
echo "<td>Transfer from ".$row["firstname"]." ".$row["lastname"]."</td>";
}
?>
Right now my tables are only showing the first and last name of the user that made the Transfer, however, I need it to display the first and last name of the user that the transaction is made to as well. The else if code is working correct, but the first part is not showing the corresponding value.
You will need to JOIN your transactions table to your users table twice, once to get each users name. Then to avoid duplicate column names overwriting the results in the output array, you will need to use column aliases. Something like this should work:
$result2 = mysqli_query($link, "SELECT t.*,
u1.firstname AS w1_firstname,
u1.lastname AS w1_lastname,
u2.firstname AS w2_firstname,
u2.lastname AS w2_lastname
FROM transactions t
INNER JOIN users u1 ON t.wallet1 = u1.wallet
INNER JOIN users u2 ON t.wallet2 = u2.wallet
WHERE t.wallet1 = '{$_SESSION["wallet"]}'
OR t.wallet2 = '{$_SESSION["wallet"]}'
ORDER BY t.id DESC
LIMIT 5 ");
Then you can access each user's names as $row['w1_firstname'] etc.:
if ($_SESSION["wallet"] == $row["wallet1"]) {
echo "<td>Transfer to ".$row["w2_firstname"]." ".$row["w2_lastname"]."</td>";
}
else if ($_SESSION["wallet"] == $row["wallet2"]) {
echo "<td>Transfer from ".$row["w1_firstname"]." ".$row["w1_lastname"]."</td>";
}
Note that ideally you should use a prepared query for this, for example:
$stmt = $link->prepare("SELECT t.*,
u1.firstname AS w1_firstname,
u1.lastname AS w1_lastname,
u2.firstname AS w2_firstname,
u2.lastname AS w2_lastname
FROM transactions t
INNER JOIN users u1 ON t.wallet1 = u1.wallet
INNER JOIN users u2 ON t.wallet2 = u2.wallet
WHERE t.wallet1 = ?
OR t.wallet2 = ?
ORDER BY t.id DESC
LIMIT 5");
$stmt->bind_param('ss', $_SESSION["wallet"], $_SESSION["wallet"]);
$stmt->execute();
$result2 = $stmt->get_result();

INSERT with LEFT JOIN

<?php
include 'connection.php';
session_start();
$noteinfo = array();
$noteinfo['note'] = $_POST['note'];
$_SESSION['noteinfo'] = $noteinfo;
if (isset($_POST['submit'])) {
if (empty($_POST['note'])) {
echo "Dobavete Komentar";
}
if (!empty($_SESSION['noteinfo'])) {
$check = mysqli_escape_string($conn,$_SESSION['userinfo']['fname']);
print_r($_SESSION['userinfo']);
$sql = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}', '{$_SESSION['userinfo']['mname']}', '{$_SESSION['userinfo']['lname']}', '{$_SESSION['userinfo']['login']}', '{$_SESSION['userinfo']['email']}', '{$_SESSION['userinfo']['phone']}')";
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
$sql2 = "INSERT INTO notes (note_text)
VALUES ('{$_SESSION['noteinfo']['note']}')";
$sql3 = "INSERT INTO users_addresses (ua_user_id,ua_address_id)
SELECT users.user_id,addresses.address_id
FROM ( VALUES () )";
if (mysqli_query($conn,$sql)) {
echo "Added";
if (mysqli_query($conn,$sql1)) {
echo "Added";
if (mysqli_query($conn,$sql2)) {
echo "Added";
if (mysqli_query($conn,$sql3)) {
echo "Mai stana toq put";
header("refresh:3 ; url=profile.php");
}
}
}
}
else{
echo "Error";
}
}
else{
header("refresh:1 ; url=zapiski.php");
}
}
?>
My question is for $sql3: I want when the forms are completed to fill the users_addresses with the id of the user and the id from the address tables.But for now the SQL doesn't fill nothing in the table users_addresses. These are my tables:
When a user is filling in values in an application and you need to look up ids for them, then a typical way to write the query looks like this:
INSERT INTO users_addresses (ua_user_id, ua_address_id)
VALUES ( (SELECT u.user_id FROM users u WHERE u.username = ?),
(SELECT a.address_id FROM address a WHERE a.address = ?)
);
That is, you are passing parameters into the query, using the parameters to look up ids, and then using those ids to insert into the junction table.
You seem to be missing the VALUES() function in your INSERT.
INSERT INTO users_addresses(ua_user_id,ua_address_id)
It should be,
INSERT INTO users_addresses(ua_user_id,ua_address_id) VALUES(some_variable,some_variable)
You could also do,
INSERT INTO users_addresses SET ua_user_id=some_variable, ua_address_id=some_variable
When it comes to selecting the data, you will need to JOIN your tables. I suggest a LEFT JOIN in this matter. It is important, that the id's that you are going to match against one another in the JOIN are coherent, so that you are able to link the tables together. It is then up to you whether you want a specific match or not in your condition, if you are parsing a user_id (i.e. WHERE clause).
Example selecting specific match:
SELECT
users_addresses.ua_id,
addresses.address_id
FROM
users_addresses
LEFT JOIN
users ON users_addresses.ua_user_id = users.user_id
LEFT JOIN
addresses ON users_addresses.ua_address_id = addresses.address_id
WHERE
users_addresses.ua_id = $some_id
Example selecting all matches:
SELECT
users_addresses.ua_id,
addresses.address_id
FROM
users_addresses
LEFT JOIN
users ON users_addresses.ua_user_id = users.user_id
LEFT JOIN
addresses ON users_addresses.ua_address_id = addresses.address_id
Let me know if this is what you are looking for, and whether you need something elaborated.
An important note, you should look into prepared statements since you are using the mysqli_* extension. It will improve your security a lot, as you are open to SQL-injections at the moment.

SELECT a value multiple time in SQL

I have a code in PHP where I want to display multiple times values, and so, even if these values are the same between them. My code is simple :
$sql = "SELECT photo from table WHERE username IN ('1','2','2') ORDER BY id DESC ";
$res = array();
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
array_push($res, $row['photo']);
}
echo json_encode($res);
But this code only display (in json) an array of two values (because the values of photo of the username 2 are the same).
What I want to achieve is to make an array with the exact same number of values of the number of username I defined WHERE username IN ('1','2','2') (so here, 3 values).
I hope you understood me, thanks for helping me !
I think what you're after is to list even the duplicates in the end result. As your SQL will only retrieve the unique items, the idea would be to include the username in the SQL result set. Then use the original list of user names ($userNames) and add in the photo for each of them.
I've used mysqli_fetch_all() to simplify the process of fetching all of the data, then used array_column() to make the username the key for the photos.
$userNames = array(1,2,2);
$sql = "SELECT username, photo
from table
WHERE username IN ('".implode("','", $userNames)."')
ORDER BY id DESC ";
$res = array();
$result = mysqli_query($con,$sql);
$photos = mysqli_fetch_all($result, MYSQLI_ASSOC);
$photos = array_column($photos, "photo", "username");
foreach ( $userNames as $user ) {
if ( isset($photos[$user])) {
$res[] = $photos[$user];
}
else {
$res[] = '';
}
}
echo json_encode($res);
You would use left join:
select t.photo
from (select '1' as username union all select '2' union all select '3'
) u left join
table t
on t.username = u.username
order by t.id desc;
Note this will return rows, even when the user name does not exist. If you want to filter those rows, remove the left so you are doing an inner join.

how can i delete rows id from the database

can somebody help me?
here is my php script...
$req = mysql_query('SELECT id, email, start_date, end_date, time_event, time_submitted, payment_method, status FROM booking_members WHERE status="Canceled"');
while($dnn = mysql_fetch_array($req))
$req1 = mysql_query('DELETE FROM booking_members WHERE id='$id');
while($dnn1 = mysql_fetch_array($req1))
{
<td class="left"><center>
<img src="images/cross.png"></img>
</td></center>
how can i get the id from $dnn['id'] in order to delete rows?
Why not just run the delete directly?
DELETE FROM booking_members WHERE status='Cancelled'
There is absolutely no reason to first select all the id's and then loop through them all deleting rows one at a time.
Mike Brant is exactly right; You should delete them without doing a lookup first. But if you wanted to access the id, you'd use:
// ... PREVIOUS
while ($dnn = mysql_fetch_array($req)) {
$delete_id = $dnn['id'];
$req1 = mysql_query("DELETE FROM booking_members WHERE id='".$delete_id."'");
// ... CONTINUE
while($dnn = mysql_fetch_array($req))
Where is the { ?
And here:
$req1 = mysql_query('DELETE FROM booking_members WHERE id='$id');
If you want the id, of last query, you must do: $dnn['id'] and not $id ( or you set $id before)...
And, for include a HTML script, in PHP script, you must use echo or print or must close the tags php ( ?> )
If you want to do a look up, and im assuming you are using dot net nuke, download the free reports module. After installing it edit it and type in the following select statement:
Select u.id,
u.username,
u.email,
b.start_date,
b.end_date,
b.time_event,
b.time_submitted,
b.payment_method,
b.status
FROM users as u
Join
booking_members as b on u.userid = b.userid
Where status="Canceled"'
this will show you the username, email, start_date, End_date, Time_event, Time_submitted, Payment_method and status of users where there status is canceled...

select * that match user postcode in mysql table?

I'm trying to display a list of users who live locally to the user who is logged in. so if the logged in session user has a postcode of 'm3 4' and 5 other users have a postcode beginning with 'm3 4' then these users will be shown to the user.
My table is laid out like this:
id | user_id | user_postcode
1 2 M3 4
2 3 SM2 7
3 4 M3 4
so in this scenario user 2 will be shown to user 4 who is logged in because their post codes match.
I'm trying to do this in mysql and it works when i put the postcode in manually like so:
AND ptb_stats.user_postcode='M3 4'
but I'm trying to make it user session specific, so if the logged in user / $_SESSION[user_id'] has the same post code as other users.
i'm trying to do it this way, but it's showing all the users without postcodes where as it should be showing the users that have matching postcodes, shouldn't it?
function get_local_users() {
global $connection;
global $_SESSION;
$query = "
SELECT *
From ptb_stats, ptb_users
WHERE ptb_stats.user_id=ptb_users.id
AND ptb_stats.user_postcode='".$_SESSION['user_postcode']."'";
$local_set = mysql_query($query, $connection);
confirm_query($local_set);
return $local_set;
}
With this answer, I assume that the $_SESSION['user_postcode'] is filled from some type of input box and the value is a valid zipCode (like "M3 4").
You can use preg_match to split the zipcode from the number and try to select zipcodes form the db. Take a look at this example:
$matches = array();
$zipCode = preg_match('/^([a-z0-9]+)/i', $_SESSION['user_postcode'], $matches);
The zipcode is now in the $matches variable at the second place ($matches[1]).
Now use this value to create a query and check if it is the same as others..
$query = "SELECT *
From ptb_stats, ptb_users
WHERE ptb_stats.user_id=ptb_users.id
AND ptb_stats.user_postcode REGEX '^" . $matches[1] . "'";
According to what you describe, I will go onto something like that.
I used prepared statement from PDO to handle the query.
function get_local_users() {
// given that it was created like this: $connection = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
global $connection;
$stmt = $connection->prepare(
"SELECT ptb_stats.*
FROM ptb_stats, ptb_users
WHERE ptb_stats.user_id = ptb_users.id
AND ptb_stats.user_id != ?
AND ptb_stats.user_postcode = (
SELECT user_postcode
FROM ptb_stats
WHERE user_id = ?
)");
$stmt->execute(array($_SESSION['user_id'], $_SESSION['user_id']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
If the user id is stored in $_SESSION['user_id'], you can get the local users with
select u.id, u.name
from ptb_users u
join ptb_stats s1 on s1.user_id = $_SESSION['user_id']
join ptb_stats s2 on s2.user_id = u.id and s2.user_postcode = s1.user_postcode
where u.id <> $_SESSION['user_id']
SQLFiddle
If you have the postcode in $_SESSION['user_postcode'], it is even easier
select u.id, u.name
from ptb_users u
join ptb_stats s on s.user_id = u.id
and s.user_postcode = $_SESSION['user_postcode']
where u.id <> $_SESSION['user_id']
SQLFiddle

Categories