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().
Related
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.
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/
I am joining two tables: customers and queries.
I am getting the full_name from the customers table and the description from the queries table.
I am wondering if it is possible to have the results of an SQL join split into arrays that correspond with the table the data came from? For example:
$STH = $DBH->prepare("SELECT queries.description, customers.full_name FROM queries INNER JOIN customers ON queries.customer_id = customers.id");
$STH->execute();
$queries = $STH->fetchAll();
At the moment, I can access my data like this: $queries[0]['description'] and $queries[0]['full_name']
However, my question is whether there is an easy way to get the data like so: $job[0]['query']['description'] and $job[0]['customer']['full_name'].
Just as teresko mentioned, I can't understand why you'd need that.
I can only imagine you want to see on the PHP code what are the table that contained the information.
Maybe you could do something like SELECT queries.description as queries_description, then your php code would look like $queries['queries_description']. Would it be enough?
You can loop through the results in PHP and convert it to the data structure you want, but you cannot (as far as I know) automatically group the data into arrays based on the source table. A (somewhat messy) alternative, using SQL is to use a multi-query and create a temp table from your original results, then select the results on a per-table basis, like so:
CREATE TEMPORARY TABLE q AS
(SELECT queries.description, customers.full_name FROM queries
INNER JOIN customers
ON queries.customer_id = customers.id
);
SELECT q.description FROM q;
SELECT q.full_name FROM q;
So, in those SELECT statements, you'll have to list all the columns that you want for each result. Then in PHP, you'll have to iterate over each resultset and put the data into arrays (or objects/whatever) as needed. Errr. A fetchAll will still not get you what you want, but a fetchAll on the first non-empty resultset will get you all the rows from queries and the 2nd will get you all the rows from customers
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.
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.