Retrieving specific ID once - php

I have a table named users and has a user_id, and a table named groups and has a group_id and also have user_id that is a foreign key reference from users's user_id.The situation is here: if the user joined a group, his/her user_id is inserted into table groups. So if the user joined two different groups, the column 'user_id' in table 'groups' will insert two or more same user_id's. Well, I just want to bring the user_id once, either he/she joined two or more groups..
I have no idea how to loop it properly without getting user_id that is the same.... I just want it to loop once...
$query_groups = mysql_query("SELECT * FROM groups");
while ($rows_g = mysql_fetch_assoc($query_groups)) {
$g_user_id = $rows_g['user_id'];
$query_users = mysql_query("SELECT * FROM users WHERE user_id='$g_user_id'");
while ($rows_u = mysql_fetch_assoc($query_users)) {
echo $rows_u['user_id'];
}
}

change your code as follows:
$query_groups = mysql_query("SELECT user_id FROM groups LEFT JOIN users ON users.user_id = groups.user_id GROUP BY groups.user_id");
while($rows = mysql_fetch_assoc($query_groups))
{
echo $rows['user_id'];
}

You are using $rows_g but the variable is namend $rows in the first while loop.
Wrong:
$g_user_id = $rows_g['user_id'];
Correct:
$g_user_id = $rows['user_id'];
But try to use joining tables, because this is an inefficient way to get the wanted data.
In your case you should use LEFT JOIN.

Related

Mysql two column Find one data in Rows using PHP

I have to try two joins but this is not going to work.
code in Codeginator.
$this->db->select('concat(firstName," ",lastName) as fullnameVisitor,users.firstName,visitorId,destinationId,count,activityStatus,created,updated');
$this->db->from('interestedprofile');
$this->db->join('users','users.userId=interestedprofile.visitorId','LEFT');
$this->db->join('users','users.userId=interestedprofile.destinationId','LEFT');
$this->db->join('interestedprofile','interestedprofile.destinationId=users.userId','LEFT');
$this->db->order_by('created','desc');
return $this->db->get()->result_array();
User Table : https://i.stack.imgur.com/ppM3s.png
Interest Table : https://i.stack.imgur.com/EbQIX.png
i have to find visitedid and destinationid users firstName and lastName in Users Table.
You don't have to use the Active Record fully to do the joins. You can use regular SQL. For example,
$query = $db->query("SELECT * FROM users;");
foreach ($query->getResult('User') as $user)
{
echo $user->name; // access attributes
echo $user->reverseName(); // or methods defined on the 'User' class
}
This Code is Work For me.
Select us1.firstName,us2.firstName from interestedprofile ip join users us1 on us1.userid = ip.visitorId join users us2 on us2.userId = ip.destinationId

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

How to check if exists element in table (mysql)

I have create a database Mysql and I am using in php. I want for each user to be checked if there is data.
I have three tables. In the table User has a unique value called ID_u and isn't auto_increment, the table Application has a unique value called ID(auto_increment) and table InformationUser has a unique value called ID(auto_increment). The tables Users and InformationUser joins with table Application.
ID_u = a user with id_u-> 1234
I'am try this:
if( ID_u exists data){
location1.php ->data
}else{
location2.php -> input information
}
I would be thankful for any help!!
I'm not sure I understand the structure of your database, but you may take a look at this:
$query = "
SELECT * FROM users u
LEFT JOIN application a
ON u.ID_u = a.ID_u
LEFT JOIN informationuser i
ON a.ID = i.ID
//Here you can specify 'WHERE u.ID_u IN (1,2,3,4)'
GROUP BY i.ID
" ;
$users = array() ; //Create storage for users. Use their ID as indeces
$result = $mysqli->query($query) ;
if ($result && $result->num_rows >= 1){
while ($row = $result->fetch_assoc()){
if (!isset($users[$row['ID_u'])){
$users[$row['ID_u']] = array() ; //Create array for a new user
}
$users[$row['ID_u']][] = array( //Fill array in with data and add it to user.
"email" => $row["email"],
"phone" => $row["phone"]
) ;
}
}
Afterwards, let's check if data exists for a user with ID = 3 (if 3 is an int):
if (!empty($users[3])){
echo "Yeah, data exists for user with ID 3" ;
}
First of all, if the user can only have one set of phone and email, it's better to save that data in the user table so that is has the following structure:
Users
ID_u
name
surename
email
phone
If you are set to keep the structure you have, my first tip is to take away the auto-increment on the table Application. That table is just meant to save the correlation between Users and InformationUser. Furthermore, the code you're looking for would be something like:
$sql = "SELECT * FROM Application WHERE ID_u = '1234'";
$result = mysql_query($sql) or die("Woops!");
if ($data = mysql_fetch_array($result)) {
include("location1.php");
}
else {
include("location2.php");
}
So you have users and you have applications. On each application there might be a different e-mail and name behind it. So you need to join and see if something exists. Something of this style
select count(*)
from Application
join InformationUser on (InformationUser.ID = Application.ID)
where
Application.ID_U = ?
The above gives you a count = 0 if both does not exist. If you want to know if both does not exists you can use an outer join.

Execute a query, use value as a variable and run another query and then print it?

I've two tables, users and coach_to_trainee. User can have multiple coaches, and the data is stored in coach_to_trainee columns coach_id and trainee_id.
I'm using coach_to_trainee table to print out data for the user, so he/she can simply see who is his/her coach.
<?php
$user = $_SESSION['login']['id'];
$q = "SELECT * FROM coach_to_trainee WHERE trainee_id='$user'";
$coachid = $db->prepare($q);
$coachid->execute();
while($row = $coach->fetchObject()){
$coachid = $row->coach_id;
echo '<li>'.INSERT_COACH_NAME.'</li>';
}
?>
However, this will only return the ID of the coach, and I need to return the name also, from table users.
How I'm supposed to do another query inside while() and use $coachid to find the correct user?
You have to use JOIN mysql clause, like this one:
SELECT u.name, u.id
FROM users u
LEFT JOIN coach_to_trainee ctt
ON u.id = ctt.coach_id
WHERE ctt.trainee_id = {$user}
You should be done with this one ;-)
Then in Your PHP use the selected values:
while($row = $coach->fetchObject()){
echo '<li>'.$row->name.'</li>';
}

sql using LIKE clause : php

I'm trying to generate a list of events that a user is attending. All I'm trying to do is search through columns and comparing the userid to the names stored in each column using LIKE.
Right now I have two different events stored in my database for testing, each with a unique eventID. The userid i'm signed in with is attending both of these events, however it's only displaying the eventID1 twice instead of eventID1 and eventID2.
The usernames are stored in a column called acceptedInvites separated by "~". So right now it shows "1~2" for the userid's attending. Can I just use %like% to pull these events?
$userid = $_SESSION['userid'];
echo "<h2>My Events</h2>";
$myEvents = mysql_query("select eventID from events where acceptedInvites LIKE '%$userid%' ");
$fetch = mysql_fetch_array($myEvents);
foreach($fetch as $eventsAttending){
echo $eventsAttending['eventID'];
}
My output is just 11 when it should be 12
Change your table setup, into a many-to-many setup (many users can attend one event, and one user can attend many events):
users
- id (pk, ai)
- name
- embarrassing_personal_habits
events
- id (pk, ai)
- location
- start_time
users_to_events
- user_id ]-|
|- Joint pk
- event id ]-|
Now you just use joins:
SELECT u.*
FROM users u
JOIN users_to_events u2e
ON u.id = u2e.id
JOIN events e
ON u2e.event_id = e.id
WHERE u.id = 11
I'm a bit confused by your description, but I think the issue is that mysql_fetch_array just returns one row at a time and your code is currently set up in a way that seems to assume $fetch is filled with an array of all the results. You need to continuously be calling mysql_fetch_array for that to happen.
Instead of
$fetch = mysql_fetch_array($myEvents);
foreach($fetch as $eventsAttending){
echo $eventsAttending['eventID'];
}
You could have
while ($row = mysql_fetch_array($myEvents)) {
echo $row['eventID'];
}
This would cycle through the various rows of events in the table.
Instead of using foreach(), use while() like this:
$myEvents = mysql_query("SELECT `eventID` FROM `events` WHERE `acceptedInvites` LIKE '".$userid."'");
while ($fetch = mysql_fetch_array($myEvents))
{
echo $fetch['eventID'];
}
It will create a loop like foreach() but simpler...
P.S. When you make a MySQL Query, use backticks [ ` ] to ensure that the string is not confused with MySQL functions (LIKE,SELECT, etc.).

Categories