SQL - Show column names from a sql result - php

Something similar has been asked before but not answered and it's not 100% the same, what i have is an SQL like:
SELECT * FROM table1 JOIN table2;
I know that I can get the columns of a table using DESC, DESCRIBE or SHOW BUT, that function doesn't allow multiple tables neither SQL queries.

Both mysqli::fetch_assoc() and PDOStatement::fetch() can return a row as an associative array, which means that the columns are indexed by column name rather than by number. You can then use the array_keys() function to extract a list of the column names, in order, from the row.

Related

MySQL Column names of any Select statement

I am making a SQL teaching program. The students will become their Database and Questions. I want to make it possible for them to write any query they want to and give them the result of it.
So it is possible that they write a query like:
SELECT Person.*, Student.ID
FROM Person JOIN Student JOIN Address
WHERE Address.housenr > 20
This makes it hard to use the
SELECT table_name, column_name
FROM INFORMATION_SCHEMA.COLUMNS;
to get the column names. It would be very nice to get those names right from the results of the query. Is it possible to do that in PHP?
You can use the fetch_fields() method to get any information about the columns in your result set. When your query returns at least one row you can use the normal fetch_assoc() method and read the keys from the returned array via array_keys().

Fetching few records from mysql database having million entries

I have a table which has million rows. It has user id as its primary key. I have an array having 500 user ids in it.
I want to select all the records from the table whose user ids are in the array. I know one method to do this is to change the array into a string and run IN query by passing the string.
But I think it is not the efficient way to do it. So kindly suggest other ways.
I am assuming that your ids are integer. Maybe you are getting this list of Ids from some other sources so that a join on mysql side is not desired solution. If yes, then find the maximum and minimum id present in your 500 Ids list. You can do this in php side. When you have the max and min value, then query mysql db with a where clause
select ...
from table_name
where min_id <= id and id <= max_id
id is the primary key so the advantage is that it is already indexed.
I have done this in the past, I am not sure that my method is the most efficient.
I create a string out of the ids: where id = a or id = b or id = c ...
then I add the select statement in front of it, and do a fetchall.
My guess is that you're getting these user IDs from another table and that you are storing them in an array. If this is correct, then you should change the query that fetches these user IDs so that it uses a join instead.
Joins will help you there, because IN() is not a good programming practice.
You can learn about joins here : http://mysqljoin.com/

PDO: fetchAll() with duplicate column name on JOIN

I have several table with similar column name in my database.
Let say TABLE 1, TABLE 2, TABLE 3 have a column named : "name". Those are not indexed columns. They contain different and independant data.
If I run a query joining these 3 tables and fetchAll() the results, there will be only one "name" entry in the resulting array since fetchAll() overwrite the column with the same name.
The regular MySQL Library let you access such results doing:
mysql_result($result,0,'TABLE1.name');
How can I let PDO append the table name before the column name like : TABLE1.name, TABLE2.name, etc.
I want to AVOID using alias in my SQL query since I have tons of tables. The only answers I found online uses alias. Is there any parameters we can feed to PDO to do what I am looking for?
You can use aliases instead of direct column names in your SELECT statement. Something like this:
SELECT
table1.name AS t1_name,
table2.name AS t2_name,
table3.name AS t3_name
-- rest of your query

How do I retrieve data with MySQL such that I won't be getting duplicate values in a single column?

I am currently working on a school system where we have a parent course and a child course (meta_courses in Moodle).
So, we have a table mdl_course_meta and it has 3 fields. Id, parent_course and child_course.
My problem is that a parent course can have many child courses so that means, for example, a parent_course = 50 can appear two times in the table which means it has 2 child courses. I just want to be able to find all the parent courses without it returning the same value twice or more times. I'm currently using this query right now which obviously doesn't do what I want:
$q = "SELECT * FROM mdl_course_meta";
I am working with PHP as well by the way.
Thanks a lot.
SELECT DISTINCT parent_course from mdl_course_meta
That should do it if you just want the course names. One thing to keep in mind, if you want other fields this is not going to work the way you want it to(how would it know which record to choose if there are multiple records with the same parent_course and you only want one).
This approach can only be used if you only want to return the parent_courses without duplicates.
DISTINCT helps to eliminate duplicates. If a query returns a result that contains duplicate rows, you can remove duplicates to produce a result set in which every row is unique. To do this, include the keyword DISTINCT after SELECT and before the output column list.
$q = "SELECT DISTINCT parent_course FROM mdl_course_meta";
If you don't want duplicate values in a single column, use GROUP BY parent_course.
In this way you are free to select any column.
If you only want distinct values for a particular column column, then you can use GROUP BY:
SELECT *
FROM mdl_course_meta
GROUP BY parent_course
The values in the other columns will be arbitrary. This will work in MySQL 5.x.
MySQL 4.x won't let you be arbitrary, so you can't mix aggregate and non-aggregate columns. Instead, you'd have to do something like this, which gets a bit complicated:
SELECT MAX(col1), MAX(col2), parent_course, MAX(col4), ...
FROM mdl_course_meta
GROUP BY parent_course
This way, the values aren't arbitrary. You've specified the ones you want.

How to create MYSQL record source for two related tables

I currently have a page that displays player information from one table named "tblplayers". The query I am currently using is:
$result = mysql_query("SELECT * FROM tblPlayers WHERE lng_RecordID_PK = '".$playerid."' ");
I have a second table named "tblMatches" containing match results for the players. I want the recordset to include the rows from "tblMatches" WHERE "P1_ID" OR "P2_ID" is equal to the "lng_RecordID_PK" field from "tblPlayers".
How can I revise my $result query so that it returns:
one row from tblPlayers
multiple rows from tblMatches
???
Thanks for helping me out.
That's called a 'join':
SELECT tblPlayers.*, tblMatches.*
FROM tblPlayers
LEFT JOIN tblMatches ON Ing_RecordID_PK IN (P1_ID, P2_ID)
You are asking about joining two tables where the second table potentially has multiple records for each one in the first table. This is a one-to-many or 1:N join, and most often done using a LEFT JOIN meaning you want everything in the "left" table, and all the records that match from the "right" table, and that you may have some records on the "left" side with no matches.
Your query would look like this:
SELECT *
FROM tblPlayers
LEFT JOIN tblMatches
ON (tblPlayers.lng_RecordID_PK = tblMatches.P1_ID
OR tblPlayers.lng_RecordID_PK = tblMatches.P2_ID)
WHERE tblPlayers.lng_RecordID_PK = #PlayerID;
Bits of advice:
Avoid selecting all columns (*) and instead select just those that you need for the query.
Consider using parameterized queries to avoid SQL injection attacks. If your variable were to be submitted or altered maliciously, it could result in compromised data or security. (See PHP Data Objects for example.)
There is no way to get rows from two different tables in the way you are describing. You could not get a row from one table, and two rows from another one. What you could is do two separate queries, or use a JOIN statement to join the two tables together, and then receive results from the resulting joined table. If you provide more information about your table structure I am sure more help can be given.

Categories