Selecting data for each user from multiple tables - php

I'm trying to add a function to a script that orders a list of users and then allows that same order SQL to be used to create an export file. I'm writing it for a piece of software that hosts basic user data in one table, and the question value I'm trying to get in another. Here's the details:
Table1 is base_user and from it I need the values of columns id, username, and email. However, I want to add the option to order/export by users with all that same data, but by their sex.
Table2 is base_question_data and from it I want to get the question 'sex' value.
Users can pick between Male or Female (Values: 1 or 2), and that info is stored in a column named intValue. I've already tried using INNER JOINS and such selecting multiple info from both tables, but where I'm getting confused is how to say "Get id, username, email, and sex for every user that is X sex" where "X sex" is the gender the user set to order/export by. I'm having a hard time figuring out how to get the specifics for the sex value for each user, but also use it to only show all those users of that value. All ideas are appreciated.
EDIT:
Forgot to mention that in the 'base_question_data' table, column 'userId' is equal to column 'id' in 'base_user' table.
This is Table1 or base_user
This is Table2 or base_question_data
To clarify what I'm trying to do:
In the 'base_user' table, I want to select ID, Username, and Email. I have this working normally, as it's a simple query. I want to, however, let users order by each user's gender. So
1)They can order the preview list by Male (questionName = sex intValue = 1) or Female (questionName = sex intValue = 2). This way, it will show all user's ID, Username, and Email who are gender 1 or 2. Using this same query, I'm trying to let them export that data as well, so they can export only users of gender 1 or 2.
My problem is the process of combining all of this data. I need to combine base_user's "id" to base_question_data's "userId" and I need to also get the value of each user by targeting base_question_data's questionName='sex' and get the intValue based on if they're ordering by Male (value=1) or Female (value=2).
I've done LEFT JOINS when combining one value to another for two tables, and while this is still two tables, I've never done it where I need to combine two different keys from two tables while also ordering them all by two different column values in one of those tables.

I agree with #rowmoin but if you use LEFT JOIN it will give null value if no entry in your base_question_data table and if you use INNER JOIN it will ignore those records from both tables which does not match so you can not get users from base_user if you do not have related entries in base_question_data table.

The query was easier than I anticipated. I will explain it in detail here.
To achieve something like this, (in which I needed one table's two values to decide what I'm getting in my other table results), I simply changed the value of 'intValue' in my query, but you can also do this by assigning a php value to let it be dynamically changed if you want. Since I'm doing a change between 1 or 2, I just have to different queries with the respective variable.
Here's my query:
SELECT * FROM ow_base_user
INNER JOIN ow_base_question_data ON ow_base_user.id = ow_base_question_data.userId
WHERE questionName='sex' AND intValue='$value';
I finally realized this morning I needed to go backwards, rather, and select my conditionals from base_question, rather than from the base_user table. Using this query, (where $value=1 for male or $value=2 for Female) I have successfully gotten to return a list of user's who match the set $value with their IDs, Username, and Email.

Related

Replace specific column data in select query?

I am trying to replace a column in the result of the select query as denoted in
This reference but unlike the example I have many columns in the table thus I can not specify the name of every column in the select query.
I tried some ways to attain the same but none seems effective.
select
*, (REPLACE(REPLACE(role_id,1,"admin"),2,"moderator") AS role_id
from user;
or
Select *
from user
where role_id = (select REPLACE(role_id,1,"admin") as role_id from user;
Here we assume only two possible values for the role_id however at certain instanced it might have to get data from another table ie a different table that holds different ids and values corresponding to them.
So is there a way to attain the following conditions in a single query:-
to replace values of some fields returned from select query (assuming many columns writing the names of all the columns individually is not feasible)
to get the replacement values from different tables for different columns in single table.
I need to implement the above conditions in one query but the changes shouldn't be in the database only the result of select query needs to be optimized.
Already referred to the following too but could not help.
Link 1
Link 2
Link 3
I am using phpmyadmin as engine and php as the implementation language.
If i have understood your question correctly, it's easier to use CASE/WHEN
SELECT *,
CASE WHEN role_id = 1 THEN "admin" WHEN role_id = 2 THEN "moderator" END AS role_id
FROM user;
But easier still maybe to have an array in PHP,
$roles = array("1" => "admin", "2" => "moderator", .... );
and look it up in the array. that will keep your query short and sweet. The advantage of this approach is that you don't need to change your query every time you add a new role. If you get a large number of roles (say dozens) you might actually want a separate table for that.

Data from MYSQL Database straight to Input fields, depending on what is written in first input field

looking for guidance/assistance on PHP, MYSQL, HTML, Previously in all the code I've been given I'm very hack and slashy, and as long as it works that's great, and if a problem arises, I deal with it as they appear.
I have a form - http://jsfiddle.net/Yrdit/yQzsh/ - on an internal project. I have 1 database that contains numerous tables, but only 2 Should matter for what I need.
In my Form I have already figured out how to populate from 1 table the username and password.
In the two tables, there is 1 column that I want to be linked. - In Table 1 it is called company_name in table 2 it is called - user_company.
Table 1 handles the companies phone number, address etc.
Table 2 handles the username / password / name.
In my Fiddle I want Phone/ Address/ City/ Zip/ Country field's to be filled in depending on what is in the Company one.
Say if in my table my company is called CompanyABC, and has its details completed in the database Table 1. I want those values put into the fields I listed above.
$Table_1 = $db->get_row("SELECT user_login,user_password,user_name,user_email FROM Table_1 WHERE (user_id = $url_user_id) limit 1;");
Above is the part of code used as a request to get the login/ name/ password. Can anyone in a similar format guide me through how I can do what I've spoken about above please?
Apologies in advance if the formatting is wrong, I read the rules but might've missed something about formatting.
Not sure if I understand your question correctly but I'm assuming you wish to pull company info from table 1 and user info from table 2. If so you can use join - assuming you have some sort of identifier field in between the two... I.e. company_id. company names could work but this would not be good approach. 1. company names can be misspelled / uper-lower case issues / indexing performance. For the example sake lets join two tables on company name.
"SELECT t1.user_login,t1.user_password,t1.user_name,t1.user_email FROM Table_1 t1 LEFT JOIN Table_2 t2 ON t2.user_company = t1.company_name WHERE t1.user_id = $url_user_id LIMIT 1"
Hopefully that is the answer you were looking for.

Perhaps joining 2 tables together when Users register

So this is my sorta first time doing an Online RPG (MMORPG), It's a browser based-Pokemon game.
In the Database, l've created 2 tables;
1.Pokemons (Columns; ID#, PokemonName, PokemonType, Level, Exp, HPoints, ATT, DEF)
2.Users (Columns; ID, Full Name, E-Mail, Username, Password)
In the Register field, they put in their info (User, Pass, Email), then chooses a Starter Pokemon to fight with. My question is how would i interpret that into a SQL/PHP command that joins the starter pokemon to that User or vise versa?
Far as l know it's
SELECT * FROM table_name;
But let's say l wanted to choose THAT user who just registered. Would the * just automatically choose that player or will it select everything from the Users list (Currently 3 rows of users in the Table).
Im reading w3schools for the moment, but needed some real-time advice on how l should go about with this. Thanks again!
thepokemonrpg.x10.mx If you guys wanna see what l mean.
This would indeed select everything from the Users table:
SELECT * FROM Users
The * doesn't mean all records, it just means all columns for any matching record. However, since there's no filter, all records happen to be matching records. If you want to only select a single record from that table, you would add a WHERE clause:
SELECT * FROM Users WHERE Username='someusername'
There are a few different ways that you can construct the SQL query to include a value like that (since someusername would likely come from a variable and not be explicitly written like that). Just be aware of SQL injection vulnerabilities when building those queries. You wouldn't want to accidentally publish a website where users can write their own database code and execute it on your server.
As for joining the tables, I currently don't see a way that you could do that. These two tables define two distinct entities, but have no way to relate to one another. There are a couple of ways you could do that, depending on how these entities are actually related. To that end:
Does a Pokemon always have exactly 0 or 1 owner? or;
Does a Person always have exactly 0 or 1 Pokemon? or;
Can a Pokemon have many owners and a Person have many Pokemons?
If the first statement is true, then you can add a UserId column to your Pokemons table and make it a foreign key to the Users table. That way every Pokemon record would indicate which User owns it.
If the second statement is true, then you can add a PokemonId column to your Users table and make it a foreign key to the Pokemons table. That way every User record would indicate which Pokemon is currently owns.
If the third statement is true, then you'd need to add a joining table to maintain this many-to-many relationship. Something like this:
PokemonUsers
------------
Id
PokemonId
UserId
Every record in this table would essentially be a link between a record in the Users table and a record in the Pokemons table.

MySQL Query to determine Value based on 3 Variables

I need to be able to pinpoint a value in a MySQL table which is defined by two variables.
On the frontend of the site, there is a form which accepts a variety of fields. For this example let’s focus on these two:
Account Number
Account Name
I have developed a script which will use an ajax script to check the “Account Number” once entered and if it finds a match will display the “Account Name” when the user tabs out of the field.
The difficulty is to find a single result from the format of the database tables. For example:
”SELECT * FROM example_table WHERE name=’$accountnumber’”
Provides a list of all the values that equal the account number, but does not provide any record of the account name.
”SELECT * FROM example_table WHERE name=’$accountname’”
Provides a list of all the values that equal the account names, but does not provide any record of the account number.
The $record value is the only common thread between $accountnumber and $accountname.
So all in all, I need assistance creating the loop which can first take the $accountnumber value to find the $record value associated with that number. Secondly it will take the determined $record value and match it to the $accountname value. There is only one $accountnumber and $accountname value per unique $record value.
UPDATED: There have been several good comments on this question. To help provide more background, there is only one table. The best discriminator available seems to be the title value. Here is a link to the table snippet to view in greater detail:
https://docs.google.com/file/d/0By2lFlhEzILjbE1uT1hkVURmczA/edit?usp=sharing
So ultimately in this sample, a user would type 246802 and the result that is filtered out would be Fred’s Account.
Sounds like these are in the same table? Is there any discriminator to tell you whether name holds an accountnumber or accountname?
In any even, with the following assumptions you could try an ugly self join:
There are only two records with the record ID you want
these are multiple columns in the same table holding different information in the ambiguous column names
there is no better way to discriminate the record type
If so, something like this self-join should get you started:
SELECT t2.name as accountnumber from example_table as t1
INNER JOIN example_table as t2 on t1.recordID=t2.recordID
WHERE t1.name='$accountname'
EDIT Note - if my assumptions are correct and if this is data you are inheriting, I feel for you and you should look to improve it's structure. If you are designing it like this, you may want to think about it some more first.
EDIT 2
You probably want to put an index on the name column (this is the discriminator I would used based on your example).
Your query can be something like this:
SELECT t1.value as accountnumber,t2.value as accountName from example_table as t1
INNER JOIN example_table as t2 on t1.record=t2.record
WHERE t1.name='accountNumber' and t2.name='accountName'
See this SQL Fiddle: http://www.sqlfiddle.com/#!2/97c2f/1

MySQL In query using results from another query?

I need some help creating a query for my mySQL database. I have recently started using JOIN and IN to select rows from my database, so I apologize for sounding like a noob.
I am not looking for an answer (although one would be nice!) but advice on where I should start with my query would be greatly appreciated. Please do not just post a link to the PHP website or to a tutorial.
In my database, users are "linked", the order is NOT important.
Table Name: UserLinks
link_ID User_1 User_2
1 10982* 34982
2 82738 16643
3 10982* 99822
4 78256 10982*
The user that I am focusing on here is user 10982
1) The first part of this query that I would like to create find the ID of the users that this user (10982) is linked to. These users are user 34982, 99822, and 78256. I imagine it is something as simple as SELECT * FROM UserLinks WHERE User_1 OR User_2 = 10982, my issue here is, how do I obtain the values - given that I cannot simply choose a row to return (I considered using an if statement... if the value of User_1 is 10982, then choose User_2. This however, seems redundant.
With this list of Users ID's, I would like to run the second part of the query, to find which Event_ID's correspond to this list of users (the ID's of the users are now UserEv_ID):
Table Name: EventUserTags
ETag_ID UserEv_ID Event_ID
1 34982* 289
2 82738 231
3 99822* 990
4 78256* 486
2) The second part of this query will use the list generated from the first query (of user ID's) to generate a list of Event_ID's. I know that you can use the IN statement and just dump this list in to the query as an array, but that means making the results of the first part of the query into an array. This again, seems redundant. I would like to know how to properly select these Event_ID's using the User ID's... I think that the JOIN Query will work, but I need some advice on how to use this.
The values of Event_ID's obtained here are 289, 990, and 486. In last part of this query I need to use this list of Event_ID's generated from the last query to match up with the data of another table, my Events table.
Table Name: Events
Event_ID Event_Order
182 8728342
289 3478792*
990 1876623*
486 9617789**
3) Lastly, I need to use the Event_ID's obtained from the last query to obtain their corresponding Even_Order. Again, I know this can be done with the IN statement (using an array) but this will not be efficient at all.
The purpose of this query is to start with a single User's ID, and find the Event_Order of every user this user is linked to.
Any help is really appreciated
This can all be done fairly simply in one query which I will write and then explain:
SELECT
Event_Order, -- I think this is the one you need, but selecting other fields anyway
Event_ID,
User_1,
User_2
FROM
Events
NATURAL JOIN EventUserTags
JOIN UserLinks ON (
UserEv_ID = User_1 AND User_2 = 10982
OR UserEv_ID = User_2 AND User_1 = 10982
)
NATURAL JOIN is a short cut for JOIN EventUserTags ON (Events.Event_ID = EventUserTags.Event_ID). It works because the keys you are joining on have the same name.
Then you join on the respective user IDs only if the link has the user you're looking for.

Categories