Converting SQL Table ID into another field in PHP - php

So I'm trying to get the following to work;
//SEARCH USERPETS TABLE FOR ANYTHING USER OWNS
$query = "SELECT * FROM userpets WHERE owner = '$username'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$userspets = $row['petid'];
//SEARCH PETS TABLE FOR LIST OF PET NAMES AND DETAILS
$query = "SELECT * FROM pets";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$petid = $row['id']
$petname = $row['petname'];
$petimg = $row['petimg']
//TURN PET ID INTO PET NAME AND IMAGE
echo "Pets: ".$userspets;
Essentially what I'm trying to do is this;
The 'userpets' table contains all 'owned' pets and the players username is displayed.
I want to grab all pets owned by that user and compare the petid with the 'pets' table.
I then want to take the pet's name and image from that table and 'echo' it onto the page.
Getting all the ids is fine, I just don't know how to make it convert the id's into the names.
Table Structure

You can use JOIN of MYSQL or Foreach of PHP
This is example by using PHP Foreach
$query = "SELECT * FROM userpets WHERE owner = '".$username."'";
$result = mysqli_query($conn, $query);
$petid = array(); // store all petid of this user
$rows = mysqli_fetch_all($result,MYSQLI_ASSOC);
foreach($rows as $row) {
$petid[] = $row['petid'];
}
$query = "SELECT * FROM pets WHERE id IN (".implode(",",$petid).")";
// implode will convert an array to string with delimete
// example array(0=>35, 1=>36, 2=>48) will be convert to "35,36,48"
// and above query should be : SELECT * FROM pets WHERE id IN (35,36,48)
$result = mysqli_query($conn, $query);
$pets = mysqli_fetch_assoc($result);
// dump it
echo "<pre>";
var_dump($pets);
echo "</pre>";
die;
Using MySQL Join
<?php
$query = "SELECT pet.id, pet.petname, pet.petimg, up.owner FROM pets as pet LEFT JOIN userpets as up ON pet.id = up.pet_id WHERE up.owner = '".$username."'";

I don't know how your tables look, but the best thing I can think of is, you have 3 tables one with Users, second with pets, and third "many to many" table lets call it ownedpets with users that own pets, because many users can own many pets. So ownedpets should have id_users that is connected to user.id and id_pets which is connected to pets_id. With that in mind I would do the fallowing query
SELECT *
FROM ownedpets
LEFT JOIN users
ON users.id = ownedpets.id_users
LEFT JOIN pets
ON pets.id = ownedpets.id_pets
WHERE users.id = $user_id
hope this helps

Related

1 JSON object, 2 queries, 2 tables

Here is my simple query:
$sql = "SELECT * FROM donations Order By userid";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()){
$json[] = $row;
}
$data['data'] = $json;
I use it to display all data from the 'donations' in a table. Fields are: userid,date,amount.
In that same table, I'd like to add firstname and lastname of corresponding userid which are stored in mymembers table. The condition should be WHERE donations.userid = mymembers.id.
I need help adding that condition for every row resulting from the $sql query.
Use join and change query to
SELECT * FROM donations
INNER JOIN mymembers on (donations.userid = mymembers.id)
Order By donations.userid

sql select from table then compare with other table in one statement

I have to tables in one database.
users
user_activate
I have to variables in php
$username = foo;
$key = jas823k123ksd34324;
Now I want to select from the table users the attribute user_id where user_username == $username
I do this with this statement
$sql = "SELECT user_id FROM users WHERE user_username = '$username'";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_assoc($result)){
$user_id = $row['user_id'];
}
Now I want to select from the table user_activate the attribute user_activate_key where user_activate_key == $key;
For this I use this statement:
$sql2 = "SELECT user_activate_key FROM user_activate WHERE user_activate_key = '$key'";
$result2 = mysqli_query($db, $sql2);
while($row = mysqli_fetch_assoc($result)){
$user_key = row['user_activate_key'];
}
Can I do both statements in one statement?
As you've written it, two seperate queries is the correct way to do it. But I suspect that there's some kind of relationship between users and user_activate that might make what you're asking for make sense. Assuming that a user_activate_key is tied to a specific user_id, you could do something like the following:
select users.user_id, ua.user_activate_key
from users u
left join user_activate ua
on u.user_id = ua.user_id
and ua.user_activate_key = '$key'
where u.username = '$username'
The LEFT JOIN means that the user will be shown even if there isn't a matching user_activate_key record.

Looping through a mysqli result

I'm trying to display a list of status updates from artists that a logged in user is following.
So far I have this:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
}
But i'm not sure how to loop through and display the returned status updates?
This isn't a strong point of mine, so any pointers would be greatly appreciated!
What prevented you from doing similar to what you'd already done for the first query? Something like follows:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
while($status_result_row = mysqli_fetch_assoc($status_result)) {
echo $status_result_row['mycol']; // This is where you know better than us
}
}
Or if those two tables artist_likes and status_updates have artist_id in common then you could just use one query with a join. (But don't know if you are asking for that).
Just for avoiding multiple query, you can use one query like this:
SELECT l.*, s.*
from artist_likes l, status_updates s
WHERE
l.artist_id = s.artist_id and
l.user_id = '1'
or
SELECT l.*, s.*
from artist_likes l
JOIN status_updates s on (l.artist_id = s.artist_id)
WHERE
l.user_id = '1'

One variable row inside another variable row

I have following script:
$sql = "SELECT * FROM `users`"
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$sql1 = "SELECT * FROM `other_table`";
$q1 = mysql_query($sql1) or die(mysql_error());
$row1 = mysql_fetch_array($q1);
$item = $row1[$row['username']];
How can I set one variable row inside another, since it does not work. Basically, I need to select username, and then select column with user username from other table, in which is written user points.
I was thinking about adding:
$sql = "SELECT * FROM `users`"
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$sql1 = "SELECT `".$row['username']."` FROM `other_table` WHERE `uid` = 1";
$q1 = mysql_query($sql1) or die(mysql_error());
$row1 = mysql_fetch_array($q1);
$item = $row1[xxxxxxxxxx]; // DONT KNOW HOW TO DEFINE IT, so it takes out found variable (there is only one).
Guess you want something like
SELECT * FROM table1 t1, table2 t2 WHERE t1.user_name = t2.user_name?
Think about using JOIN
$sql = "SELECT * FROM users;";
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$sql1 = sprintf("SELECT * FROM other_table where username='%s';", $row['username']);
$q1 = mysql_query($sql1) or die(mysql_error());
$row1 = mysql_fetch_array($q1);
// now $row1 contains the tuple of this user and could access the variables are you would
// normally do e.g. $row1['ID']
SELECT * FROM users AS u INNER JOIN other_table AS o ON u.username = o.username
I'm assuming you want to do this because you want to be able to access all the rows from either table where a particular user name is the same (e.g. the data from users where username="john" and the data from other_table where username="john" for all usernames). No need to nest a result set to do this, just use a JOIN statement and then you can access all the columns as if it was a single result set (because it is):
$sql = "SELECT * FROM users AS u INNER JOIN other_table AS o ON u.username = o.username";
$q = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($q);
$item = $row['any_column'];
FYI you should list out the column you want to retrieve instead of using *, even if you want to retrieve them all, as it is better practice in case you add new columns in the future.

Get a number in one table and print the number's referenced name in another table

I need to create a friend system, but my loop always skips the first match and sometimes it prints copies of the same name
$result = mysql_query("SELECT * FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id");
while($row = mysql_fetch_array($result))
{
if ($row['username_id'] == 1)//the 1 will be a variable, username_id is in friends
$count = $row['friendname'];//friendname is in friends
if ($row['id'] == $count)//id is in users
echo $row['username'];//username is in users
}
Can someone see what my problem is ?
2 things:
if ($row['username_id'] == 1)
you should put that in your sql:
$result = mysql_query("SELECT username, friendname FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id where tbusers.id = ".$yourVariable);
In your query, user and friend are linked, and can only be equal.
Now, this:
$count = $row['friendname'];//friendname is in friends
if ($row['id'] == $count)//id is in users
is equal to
if ( $row['id'] == $row['friendname'] )
this sounds plain wrong. You compare a numerical id with a name. Moreover, your sql query already retrives all friends from users. In the version I showed here, it retrieves only friends of the user you are interested in.
finally, you print (echo) the name of the user, not of the friend. In my opinion the following code will do what you want:
$result = mysql_query("SELECT friendname FROM tbfriends WHERE username_id = ".$yourUserVariable);
while($row = mysql_fetch_array($result))
{
echo $row['friendname']; // or better: echo $row['friendname'], '<br>';
}
edit: after comment...
so if ( $row['id'] == $row['friendname'] ) means the user is his own friend. can that happen?
this code shall print what you want, friend names.
/*
$result = mysql_query("
SELECT username as friend_name,
friendname as friend_id,
username_id as user_id
FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id
WHERE tbusers.id = ".$yourVariable);
*/
$result = mysql_query("
SELECT username as friend_name,
friendname as friend_id,
username_id as user_id
FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.friendname
WHERE tbfriends.username_id = ".$yourVariable);
while($row = mysql_fetch_array($result))
{
echo $row['friend_name']; // or better: echo $row['friend_name'], '<br>';
}

Categories