I have a MYSQL table that is 1275 fields wide. Each row in the table represents a single class of students, with 17 fields per student, X up to 75 students per class, so 17 X 75 = 1275 fields.
I have devised an SQL UNION query that successfully pulls the students into another table, with each student on a single row.
Now, I want to use this UNION query as part of a PHP program. I have “imported” the query into PHP as it is. But, isn’t there a way to use PHP to shorten the SQL query? Shamelessly, here is my code:
$sql = "
INSERT INTO $t_mem2
SELECT localcourse
, statecourse
, coursetitle
, semester
, section
, teachercode
, teachername
, meetingcode
, classpop
, student_id_01 AS student_id
, sex_01 AS sex
, dob_01 AS dob
, grade_01 AS grade
, ethnic_01 AS ethnic
, last_name_01 AS last_name
, first_name_01 AS first_name
, $c_sch AS sch_code
FROM $t_mem1
UNION
SELECT localcourse
, statecourse
, coursetitle
, semester
, section
, teachercode
, teachername
, meetingcode
, classpop
, student_id_02 AS student_id
, sex_02 AS sex
, dob_02 AS dob
, grade_02 AS grade
, ethnic_02 AS ethnic
, last_name_02 AS last_name
, first_name_02 AS first_name
, $c_sch AS sch_code
FROM $t_mem1
UNION
SELECT localcourse
, statecourse
, coursetitle
<...snip..............................>
, teachername
, meetingcode
, classpop
, student_id_75 AS student_id
, sex_75 AS sex
, dob_75 AS dob
, grade_75 AS grade
, ethnic_75 AS ethnic
, last_name_75 AS last_name
, first_name_75 AS first_name
, $c_sch AS sch_code
FROM $t_mem1
ORDER
BY localcourse
, statecourse
, semester
, section
, teachername
, meetingcode
, last_name
, first_name" ;
First off, this query indicates that your database schema is very, very poor.
That aside, yes, you can shorten the query with PHP:
This will “shorten the query” by generating it in PHP code. If, on the other hand, you’re looking to make the query as it hits the database shorter, that is also possible; just modify the loop above to start
$queryanew in each iteration, and glom all the results together in one array. You’ll end up with 75 queries made, and PHP will perform the UNION.