Get MySQL table.column named records with PHP - php

For example:
I have the normal column name:
SELECT column FROM....
The way i retrieve it in PHP:
$var = $row["column"];
What i want to know is how to retrieve column records which are named with column and table:
SELECT table.column FROM...

It works the exact same way, it's not going to be prefixed with a table.
so if you do a SELECT table.* FROM ..., and one of the column names is tacos. you can still do $row['tacos'].
Now, if you're doing multiple tables (joins) it can get ambiguous if they have the same names, such as "id". So you can alias them... SELECT table.column as new_name FROM ...

You won't get them returned with table.column. Perhaps use an alias? Could use a delimiter between table / field name part.
SELECT column AS tableName_ColumnName FROM....

It sounds to me like you're trying to select from multiple tables which can be done by using joins:
Lets say you have 3 tables that you need to obtain information from all by a unique ID. You can accomplish this by using a left join:
SELECT a.uniqid, a.testingDate, a.testscore, a.testresults,b.email_addy, b.phone1, c.testlevel as tlevel
FROM Tbl1 a
LEFT JOIN Tbl2 b
ON a.Tbl1 = b.Tbl2
LEFT JOIN Tbl3 c
on a.Tbl1 = c.Tbl3
you can then pull the information just as you always do: $var = $row['testingdate']

Related

Missing some column names on a multiple table query [duplicate]

I have two tables in my database:
NEWS table with columns:
id - the news id
user - the user id of the author)
USERS table with columns:
id - the user id
I want to execute this SQL:
SELECT * FROM news JOIN users ON news.user = user.id
When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?
You can set aliases for the columns that you are selecting:
$query = 'SELECT news.id AS newsId, user.id AS userId, [OTHER FIELDS HERE] FROM news JOIN users ON news.user = user.id'
You can either use the numerical indices ($row[0]) or better, use AS in the MySQL:
SELECT *, user.id AS user_id FROM ...
I just figured this out. It's probably a bad practice but it worked for me in this case.
I am one of the lazy people who doesn't want to alias or write out every column name with a table prefix.
You can select all of the columns from a specific table by using table_name.* in your select statement.
When you have duplicated column names, mysql will overwrite from first to last. The data from the first duplicated column name will be overwritten when it encounters that column name again. So the duplicate column name that comes in last wins.
If I am joining 3 tables, each containing a duplicated column name, the order of the tables in the select statement will determine what data I am getting for the duplicate column.
Example:
SELECT table1.* , table2.* , table3.* FROM table1 LEFT JOIN table2 ON table1.dup = table2.dup LEFT JOIN table3 ON table2.dup = table3.dup;
In the example above, the value of dup I get will be from table3.
What if I want dup to be the value from table1?
Then I need to do this:
SELECT table3.* , table2.* , table1.* FROM table1 LEFT JOIN table2 ON table1.dup = table2.dup LEFT JOIN table3 ON table2.dup = table3.dup;
Now, table1 comes last, so the value of dup will be the value from table1.
I got the value I wanted for dup without having to write out every single freaking column and I still get all of the columns to work with. Yay!
I know the value of dup should be the same in all 3 tables, but what if table3 doesn't have a matching value for dup? Then dup would be blank in the first example, and that would be a bummer.
#Jason. You are correct except that php is the culprit and not mysql. If you put your JOIN in Mysql Workbench you will get three columns with the exact same name (one for each table) but not with the same data (some will be null if that table has no match for the JOIN).
In php if you use MYSQL_NUM in mysql_fetch_array() then you will get all columns. The problem is when you use mysql_fetch_array() with MYSQL_ASSOC. Then, inside that function, php is building the return value like so:
$row['dup'] = [value from table1]
and later on...
$row['dup'] = [value from table2]
...
$row['dup'] = [value from table3]
So you will get only the value from table3. The problem is that a result set from mysql can contain columns with the same name but associative arrays in php don't allow duplicate keys in arrays. When the data is saved in associative arrays, in php, some information is silently lost...
Another tip: if you want to have cleaner PHP code, you can create a VIEW in the database, e.g.
For example:
CREATE VIEW view_news AS
SELECT
news.id news_id,
user.id user_id,
user.name user_name,
[ OTHER FIELDS ]
FROM news, users
WHERE news.user_id = user.id;
In PHP:
$sql = "SELECT * FROM view_news";
You can do something like
SELECT news.id as news_id, user.id as user_id ....
And then $row['news_id'] will be the news id and $row['user_id'] will be the user id
I had this same issue with dynamic tables. (Tables that are assumed to have an id to be able to join but without any assumption for the rest of the fields.) In this case you don't know the aliases before hand.
In such cases you can first get the table column names for all dynamic tables:
$tblFields = array_keys($zendDbInstance->describeTable($tableName));
Where $zendDbInstance is an instance of Zend_Db or you can use one of the functions here to not rely on Zend php pdo: get the columns name of a table
Then for all dynamic tables you can get the aliases and use $tableName.* for the ones you don't need aliases:
$aliases = "";
foreach($tblKeys as $field)
$aliases .= $tableName . '.' . $field . ' AS ' . $tableName . '_' . $field . ',' ;
$aliases = trim($aliases, ',');
You can wrap this whole process up into one generic function and just have cleaner code or get more lazy if you wish :)
When using PDO for a database interacttion, one can use the PDO::FETCH_NAMED fetch mode that could help to resolve the issue:
$sql = "SELECT * FROM news JOIN users ON news.user = user.id";
$data = $pdo->query($sql)->fetchAll(PDO::FETCH_NAMED);
foreach ($data as $row) {
echo $row['column-name'][0]; // from the news table
echo $row['column-name'][1]; // from the users table
echo $row['other-column']; // any unique column name
}
If you don't feel like aliassing you can also just prefix the tablenames.
This way you can better automate generation of your queries. Also, it's a best-practice to not use select * (it is obviously slower than just selecting the fields you need
Furthermore, only explicitly name the fields you want to have.
SELECT
news.id, news.title, news.author, news.posted,
users.id, users.name, users.registered
FROM
news
LEFT JOIN
users
ON
news.user = user.id
Here's an answer to the above, that's both simple and also works with JSON results being returned. While the SQL query will automatically prefix table names to each instance of identical field names when you use SELECT *, JSON encoding of the result to send back to the webpage, ignores the values of those fields with a duplicate name and instead returns a NULL value.
Precisely what it does is include the first instance of the duplicated field name, but makes its value NULL. And the second instance of the field name (in the other table) is omitted entirely, both field name and value. But, when you test the query directly on the database (such as using Navicat), all fields are returned in the result set. It's only when you next do JSON encoding of that result, do they have NULL values and subsequent duplicate names are omitted entirely.
So, an easy way to fix that problem is to first do a SELECT *, then follow with aliased fields for the duplicates. Here's an example, where both tables have identically named site_name fields.
SELECT *, w.site_name AS wo_site_name FROM ws_work_orders w JOIN ws_inspections i WHERE w.hma_num NOT IN(SELECT hma_number FROM ws_inspections) ORDER BY CAST(w.hma_num AS UNSIGNED);
Now in the decoded JSON, you can use the field wo_site_name and it has a value. In this case, site names have special characters such as apostrophes and single quotes, hence the encoding when originally saving, and the decoding when using the result from the database.
...decHTMLifEnc(decodeURIComponent( jsArrInspections[x]["wo_site_name"]))
You must always put the * first in the SELECT statement, but after it you can include as many named and aliased columns as you want, as repeatedly selecting a column causes no problem.
There are two approaches:
Using aliases; in this method you give new unique names (ALIAS) to the various columns and then use them in the PHP retrieval.
e.g.
SELECT student_id AS FEES_LINK, student_class AS CLASS_LINK
FROM students_fee_tbl
LEFT JOIN student_class_tbl ON students_fee_tbl.student_id = student_class_tbl.student_id
and then fetch the results in PHP:
$query = $PDO_stmt->fetchAll();
foreach($query as $q) {
echo $q['FEES_LINK'];
}
Using place position or resultset column index; in this, the array positions are used to reference the duplicated column names. Since they appear at different positions, the index numbers that will be used is always unique.
However, the index positioning numbers begins at 0. e.g.
SELECT student_id, student_class
FROM students_fee_tbl
LEFT JOIN student_class_tbl ON students_fee_tbl.student_id = student_class_tbl.student_id
and then fetch the results in PHP:
$query = $PDO_stmt->fetchAll();
foreach($query as $q) {
echo $q[0];
}

How to change column name while joining the query in mysql

I need to change the column name while joining the MySQL query. I am explaining my code below.
select * from grc_action left join grc_users on grc_action.action_owner=grc_users.user_id
I am giving my table below.
grc_action:
id name action_owner
grc_users:
user_id name
The above is my table structure and as both has same column name i.e-name here I need to change the grc_users table column i.e-name while fetching the record. Please help me to solve this problem.
You can use AS
SELECT table1.name AS exampleName, table2.name AS otherName FROM sometable
You can also use this on tables:
SELECT vltn.id, vltn.name FROM veryLongTableName AS vltn
You dont need to type the AS, you can just do SELECT table1.name exampleName to shorten it, but it increases readbility and maintanability to write it, so I recommend doing it with AS.
You may assign different aliases to the name columns from the two different tables.
select
ga.id,
ga.name as action_name,
ga.action_owner,
gu.user_id,
gu.name as user_name
from grc_action ga
left join grc_users gu
on ga.action_owner = gu.user_id;
Note that I also used table aliases which make the query easier to read. In general, doing SELECT * is undesirable, and it is usually better to explicitly list the columns you want.
select *
from grc_action
left join grc_users on grc_action.action_owner=grc_users.user_id
changed query use this query
select *,grc_users.name as grcuser_name,grc_action.name as grcaction_name
from grc_action
left join grc_users on grc_action.action_owner=grc_users.user_id
Here geting two name like this
grcuser_name ,
grcaction_name

How to get value from one table column when two columns of the same name exist in an sql join

I am currently faced with the problem of trying to get a value when I have joined two tables with columns of the same name eg: table1.date and table2.date (date is different in each table) how would I get the "date" of table 1 in this instance.
I am currently running
while($row = $mysqliquery->fetch_object()) {
is there any way that I could use some form of syntax to retrieve the date from table 1 within the following code
$row->date eg $row->table1.date or something
If not how else would I be able to accomplish this?
Thanks.
You should differentiate between 2 columns with the same name by using an alias for one or both of the 2 columns in the query like this
SELECT a.`date`, b.`date` as b_date
FROM table1 a
JOIN table2 b ON a.id = b.a_id
WHERE some specific criteria
Now when your retrieve the ROW each date has its own unique name i.e.
$row->date;
$row->b_date;
I was thinking more along the lines of this ( ficticious ) pseudo sql
select a.`account_id`, a.`date` as 'account_date', u.`date` as 'signup_date'
from `accounts` a
left outer join `users` u on u.`uid`=a.`uid`
Each table has a column called date but in the sql they are each referenced with a unique alias. You cannot have two columns in the same query with the same name or you'll get errors, so you give them an alias. The tables are also aliased in this code - it really helps simplify things in my opinion... Anyway, just a quick example to illustrate how you might approach this - others may have a different approach from which I might learn new tricks

Searching multiple tables in MySQL database

I have several different tables in my database(mySQL).
Here are the relevant coumns for the tables
table_tournaments
tournamentId
tournamnetName
tournamentStatus
table_tournament_results
tournamentId
playerId
playerName
playerRank
tournamnetParticipants
table_players
playerId
playerName
The tournaments table contains the information about the tournament, the tournament results table shows the results from that table
I want to search the tournaments table by name and then with the returned results get the information from the tournament results table.
SELECT * FROM `tournaments` `WHERE` `tournamentName` LIKE "%Query%"
I'm not sure how to go about this, maybe I need to do something via PHP, any and all help is appreciated.
You can get the results you want with a join operation.
This is an example of an outer join, returning all rows from t that have the string 'foo' appearing as part of tournament_name, along with any matching rows from r.
A relationship between rows in the two tables is established by storing a common value in the tournamentId column of the two tables. The predicate in the ON clause specifies the condition that determines if a row "matches".
SELECT t.tournamentId
, t.tournamentName
, t.tournamentStatus
, r.playerId
, r.playerName
, r.playerRank
FROM table_tournaments t
LEFT
JOIN table_tournament_results r
ON r.tournamentId = t.tournamentId
WHERE t.tournament_name LIKE '%foo%'
ORDER
BY t.tournamentId
, r.playerId
The t and r that appear after the table names are table aliases, we can qualify references to the columns in each table by prefacing the column name with the table alias and a dot. This makes the column reference unambiguous. (In the case of tournamentId, MySQL doesn't know if you are referring to the column in t or r, so we qualify it to make it explicit. We follow this same pattern for all column references. Then, someone reading the statement doesn't need to wonder which table contains the column playerId.
Your Query may be like this
SELECT a.*, b.tournamnetName FROM table_tournament_results a
left join table_tournaments on a.tournamentId=b.tournamentId
WHERE b.tournamnetName LIKE "%Query%"

Msql Inner Join Query Dilemma - Need Joined Auto Increment Value

I have two mysql tables that I am querying together and the query works fine. The tables are car and requests
The problem is that i need both the auto increment id's and it only gives me one.
The one it gives me is not the joined tabled.
Here is my query so far
SELECT * FROM `car` INNER JOIN `requests` ON `car`.`make_id` = `requests`.`make_id` WHERE `car`.`user_id` =21
I just need to someway get the auto increment id of the requests table.
As always stack exchange is the best place to come for answers so thanks in advance!
Just specify your query as this and you'll get both but with different names:
SELECT `car`.id AS car_id, `requests`.id AS request_id, *
FROM `car`
INNER JOIN `requests` ON `car`.`make_id` = `requests`.`make_id`
WHERE `car`.`user_id` =21
Note that you will still have an ID column which SHOULD be the requests.id, just diregard it and use car_id and request_id...
When you have to join tables and table contains same name than it creates an ambiguous situation. So always use table name or table alias with column name Like this
SELECT t.column
FROM table as t
OR
SELECT table.column
FROM table

Categories