1

I have a table which one column contains a comma seperated value. I need to, within the query, get those values, explode them, and do a query to another table.

Let me explain the structure.

Table 1: courses. Columns we are worried about for this example:

courses.id, courses.products

This will return a value

$query['id']-> 1000
$query['products']-> 1,5

Within the query I need to pull the product name for each product from the products table

so

products.productname

even if i have to create 5 productname columns in the query because no one should have more than 5 products.

The point of all of this is I have to dump this to a spreadsheet and i need to have the product names in there.

To accomplish the CSV dump I have this code. ( I already have the query written however right now just returning "1,5" instead of product names

 $query = " QUERY GOES HERE ";
 $result = mysql_query($query, $db) or die(mysql_error());
 if (!$result) die('Couldn\'t fetch records'); 
 $num_fields = mysql_num_fields($result); 
 $headers = array(); 
 for ($i = 0; $i < $num_fields; $i++) 
 {     
        $headers[] = mysql_field_name($result , $i); 
 } 
 $fp = fopen('php://output', 'w'); 
 if ($fp && $result) 
 {     
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="export.csv"');
        header('Pragma: no-cache');    
        header('Expires: 0');
        fputcsv($fp, $headers); 
        while ($row = mysql_fetch_row($result)) 
        {
         fputcsv($fp, array_values($row)); 
      }
 die; 
 } 
Tony Hinkle
  • 4,706
  • 7
  • 23
  • 35
phpman13
  • 37
  • 1
  • 1
  • 5
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Jan 21 '16 at 14:20
  • Thank you Tony. I know. This application is just massive and written so that each page has queries at the top instead of a function based central place. It began being developed in DreamWeaver and has grown to be a massive system. One of my objectives for Q1 is to move over to a function based system so no queries or sql operations are handled on a per page basis. – phpman13 Jan 21 '16 at 14:27

1 Answers1

0

A quick solution for your case:

$course_id = intval( $_GET['id'] );
// get the id 1000
$result = mysql_query( "SELECT `products` FROM `courses` WHERE `id`=" . $course_id );
$course = mysql_fetch_assoc( $result ) or exit( "Invalid ID" );
$result = mysql_query( "SELECT `id`,`productname` FROM `products` WHERE `id` IN (".$course['products'].")" );
// this will result in "SELECT id,productname FROM products WHERE id IN (1,5)"
//
// rest of your code

If you don't export your data every second or so you should be fine with these two queries.

You now experience why it is bad database design to store multiple values comma separated in a single database field. If you are restructuring the application this would be a good time to refactor your database and store every product <-> course affiliation in a single row. If your courses table only has these two columns, you can do it like this:

id   | product
--------------
1000 | 1
1000 | 5

If your table has more fields related to the course, you should move the column products into its own table as pictured above. That's the usual database structure for a many to many relationship.

Initially I expected to get your results in a single query with one of these queries, but for some reason I always end up with only one record, and I currently don't have the time to drill deeper into it.

-- try #1
SELECT products.id,products.productname 
FROM products JOIN courses ON products.id IN (courses.products)
WHERE courses.id=1000

-- try #2
SELECT products.id,products.productname 
FROM products 
WHERE products.id IN (
    SELECT courses.products 
    FROM courses 
    WHERE courses.id=1000
)

Last, but not least, you've already been given the advice to stop using the deprecated mysql_* functions. I know it's difficult to rewrite an existing application, I've been down that road myself. My experience is that it is best to do this along the way, just define a second database connection using mysqli or PDO, whatever you are more comfortable with. Every time you change something database related in a script rewrite it with the newer API. You will have a little more overhead while you do this, but not noticeably and it is way easier than rewriting everything at once.

Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78