Select user if the user has data on another table - php

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

Related

Many to many relationships - Moving data from many tables to a single table

I have a table with users and one with labels
A label can have many users and a user can have many labels, so a Many to Many relationship
A joining table is needed, that's why I have label_user
Below you can see pictures of what they contain with example data:
Users:
https://i.stack.imgur.com/E5E6O.png
Labels:
https://i.stack.imgur.com/1NFjq.png
label_user:
https://i.stack.imgur.com/tW2Uo.png
Let's say I have 5000 users and I can sort them by gender. Let's say 2800 of them are males, how can I assign them all to a label?
Here's some things I tried:
public function add_users_to_label($label_id, $condition, $value)
{
$db = new Database();
$conn = $db->db_connect();
$label_id = escape_string($conn, $label_id);
$query = $conn->query("INSERT INTO `label_user`(`label_id`, `user_id`) SELECT :label_id, psid FROM `iris_messenger_users` WHERE $condition = $value");
$query->bind_param("iss", $label_id, $condition, $value);
if ($query->execute()) {
return true;
}
else {
return "Error inserting data: " . $conn->error . "\n";
}
}
On the user side I have a simple form with select that let's you select a label and then this code:
if(isset($_POST['label-select'])) {
if ($_GET['show_only_gender'] == 'male') {
$condition = 'gender';
$user->add_users_to_label($_POST['label-select'], $condition, $_GET['show_only_gender']);
}
}
Basically, I want to get all users that are male and assign them to a label and put that into label_user with respectively the label_id and the user_id(psid)
Even if this worked I'd still have to do it 2699 times more. What can I do here to optimize and make it to run with 1 query if possible?
I don't think using foreach and running it as much times as there are users is the best option, is it?
Is there any better approach I can take to make this possible?
Although what you are describing does not make sense to have a "label" associated with a person for this specific component, the gender is already on the user table you should be able to get all male based on
select * from user where gender = 'male'
no need to JOIN to a label table on this field. Similarly if you were trying to find people based on a name starting with something... you would not create a label for the name either. Query directly from the table that has that specific component association.
Now, to answer your question, how to insert into the label table for each instance in bulk, you could do something like... I am doing this based on some label ID = 123 as just an example in your labels table that represents gender.
I am doing a LEFT-JOIN in the select so we dont try to add for any user IDs that are already on file do not try to get re-added.
insert into label_user
( label_id,
user_id )
select
123 as label_id,
U.id as user_id
from
users U
left join label_user LU
on U.id = LU.user_id
AND LU.label_id = 123
where
U.gender = 'male'
AND LU.user_id IS NULL
You obviously need to adjust for php.

PHP/MySQL Echo from multiple tables

For a schoolproject we have to make a website that interacts with a myphp database. We want to pull data from two different tables in the database, but when we try to echo the data, only data from the first table is shown.
Out two tables are: TICKET and VISITOR
This is our code:
include 'login.php';
$sql = mysql_query("SELECT * FROM TICKET VISITOR ",$mysql)
or die("The query failed!");
mysql_close($mysql)
or die("Closing the connection failed!");
if (!$sql) {
echo 'Could not run query: ' . mysql_error();
exit;
}
echo "<br/>";
while ($row = mysql_fetch_row($sql)) {
echo $row[0];
echo " ";
echo $row[1];
echo " ";
echo $row[2];
echo "<br/>";
}
basically the comments say it already: you can use joins for this task. However I think what you need is a proper introduction into the options and what it all means, so let me try help you there:
First question: What is your problem? If you want to get data from two tables indepedently then what you have two do is to make to separate queries. You more or less run this:
//first run this query
$sql = mysql_query("SELECT * FROM TICKET ",$mysql)
//Run the query and process the data
//then run this query
$sql = mysql_query("SELECT * FROM VISITOR ",$mysql)
//Process this data, too
What you probably actually want to do is to get data from ONE table based on data from ANOTHER table. For example you want to get some data about users and in one table you have their email address and their street address and in the other table you have their name. So you JOIN both tables together based on some information (key) they both contain. So then you go from
TABLE 1: id | email | address
TABLE 2: id | firstname | lastname
To this form:
NEW TABLE: id | email | address | firstname | lastname
There are different kinds of joins. The code for this could look something link this:
$sql = mysql_query("SELECT table1.id, table1.email, table1.address, table2.firstname, table2.lastname FROM TABLE1 LEFT JOIN TABLE2 ON (table1.id = table2.id)",$mysql)
As said before joins are common and properly explained elsewhere. I find this a good tutorial but of course the mentioned documentation (https://dev.mysql.com/doc/refman/5.7/en/join.html) also explained it maybe a bit more condensed.
Option 1 join
SELECT * FROM TICKET INNER JOIN VISITOR ON NAME;
NAME here is a column name maybe id
Option 2 UNION
SELECT * FROM TICKET UNION SELECT * FROM VISITOR;
As per your code just insert comma (,) after first table. See below -
$sql = mysql_query("SELECT * FROM TICKET, VISITOR ",$mysql)
or die("The query failed!");
Also you can use the inner join if any foreign key used on second table.
Use also union.

How to Display data from 2 different Database

I have an hard time to retrieve data in a table from MySQL database.
I have 2 different database that cannot be merge but there is a table in the first database that is identical to the second database.
Description Database 1 table: areas : ar_id, name, password.
Description Database 2 table: user : id, username, pass.
Now, When the user Login, He logs in the 2nd database. in each page of the user I have use $_SESSION['username'] to call the username.
Importantly, In every page, I have table that displays data from different tables using the username in the 2 Database; this else the SQL to be specific and only provide each user with their own information. and That's Ok. This is the SQL:
SELECT Client_table.Name, Client_table.Client_Id FROM Client_table, user WHERE user.username = '" . $_SESSION['username'] . "' AND Client_table.Branch = user.area Order by Name ASC
In one of the page, I totally using the 1st Database with this SQL to display data in the table :
select site_id, site_name from sites WHERE srep_id = 5
AND status = 1 or status = 2
order by site_name asc
QUESTION: I would like to display this SQL data in a table by using the username or id from the 2nd database BUT is returns Empty Table (I include both Database in this page). This is my current SQL but still not displaying anything:
SELECT cl.client_name, st.site_id, st.site_name
FROM Database1.sites st
JOIN Database2.user u ON u.id = st.ar_id
JOIN Database1.clients cl ON cl.client_id = st.client_id
WHERE Database1.st.name = '".$_SESSION['username']."'
AND st.status > 0
ORDER BY st.site_name ASC
NOTE: This is a major problem that took me almost a week!
Please some one help!
I think I have an answer.
After browsing and doing some search, I sound that I can make use of the $_SESSION here and Also, This was my final SQL Statement that Helped me to Connect the 2 Database from the same SQL Statement by using variable in PHP Script.
session_start();
$result = mysql_query("SELECT cl.client_name, st.site_id, st.site_name, ar.rep_id
FROM sites st
JOIN areas ar ON ar.rep_id = st.srep_id
JOIN clients cl ON cl.client_id = st.client_id
WHERE st.srep_id = '".$_SESSION['userarea']."'
AND st.status > 0
ORDER BY st.site_name ASC");

Retrieving specific ID once

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.

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