tnash
tnash

Reputation: 385

fill MySQL result into a grid

I have a table with project files and i am selecting project files that have the same date and display them in a row. For example:

date x --- a b c d
date y ---e f g h
date z----- i j

each row has 4 places to hold the result as i don't anticipate having more than 4 projects per day. I have used the query below to get distinct dates

$sql = "SELECT DISTINCT date FROM project_files WHERE projectNumber = something";
$result = mysql_query($sql) ;

Is there an easy way of getting data for each row and displaying it?

Upvotes: 1

Views: 3432

Answers (2)

Mike
Mike

Reputation: 318

Try this:

<html>
<head>
  <title>
    PHP MySQL Test
  </title>
</head>
<body>

<?php
  $db_host = 'localhost';
  $db_user = 'root';
  $db_pwd = 'YOUR_DB_PASSWORD';
  $database = 'YOUR_DB_NAME';
  $table_name = 'project_files';

  if (!mysql_connect($db_host, $db_user, $db_pwd)) {
    die("Can't connect to database");
  }

  if (!mysql_select_db($database)) {
    die("Can't select database");
  }

  $result = mysql_query("SELECT * FROM $table_name") or die("Query to show fields from table failed");
  $fields_num = mysql_num_fields($result);

  echo "<h1>Database: $database</h1>";
  echo "<h2>Table: $table_name</h2>";
  echo "<table border='1'><tr>";

  for($i=0; $i<$fields_num; $i++) {
    $field = mysql_fetch_field($result);
    echo "<td>{$field->name}</td>";
  }
  echo "</tr>\n";

  while($row = mysql_fetch_row($result)) {
    echo "<tr>";
    foreach($row as $cell) {
      echo "<td>$cell</td>";
    }
    echo "</tr>\n";
  }
  mysql_free_result($result);
?>

</body>
</html>

Upvotes: 2

symcbean
symcbean

Reputation: 48367

You've not said where/how you store the project files (a,b,c..). But assuming they are project_files.file....

 SELECT date, GROUP_CONCAT(file) AS list_of_files
 FROM project_files
 WHERE project_number = something  
 GROUP BY date;

(BTW using reserved words for column names is a messy practice).

Upvotes: 0

Related Questions