How can I group values from a database using <td> and rowspan? - php

So, I am reading some values from a database. Such as 'result', 'team', 'league' from a database. I am trying to display, in a <table>, results of the specific team grouped by league, something like this:
That is assuming my database contains the following data:
result1 team1 league1
result2 team1 league1
result100 team1 league2
result101 team1 league2
result88 team1 league2
I have tried a lot of stuff and yet I can't get it to work. Also, the league cell must have a rowspan equal to the number of results detected in the specific league. This can be done with mysql_num_rows, but I don't know exactly where to place it. So how can I get this table to work? Thanks a lot!

Groupng the output by league is a simple matter of doing a break-sort on the results of your query. Since your question doesn't
include your table schema, or any php code, I've made some assumptions about your table, and will leave opening the connection to
your DB, and executing the sql statement to you.
$qstr = "SELECT league, team, event
FROM table
ORDER BY league, team, event";
// Execute query, get results into associative array $allrows
$league = "";
$col1 = "";
$col2 = "";
echo "<table>\n";
foreach($allrows as $rowno => $row) {
if($league != $row['league']) {
if($league != "") {
echo "<tr>\n";
echo "<td>".$col1."</td>";
echo "<td>".$col2."</td>";
echo "</tr>\n";
}
$league = $row['league'];
$col1 = $league;
$col2 = "";
}
$col2 .= $row['team']." got ".$row['event']."<br />\n";
}
echo "<tr>\n";
echo "<td>".$col1."</td>";
echo "<td>".$col2."</td>";
echo "</tr>\n";
echo "</table>\n";

I have try'd some way and it worked for me I hope it works for you...
Look at the code:
$db = new PDO('mysql:host=localhost;dbname=you_dbname', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT league, result, team FROM matches_info';
$stmt = $db->query($sql);
echo "<table border=\"1\">";
while($row = $stmt->fetch()){
echo '<tr>
<td rowspan="3">'.$row['pcid'].'</td>
<tr><td>'.$row['pid'].' got '.$row['pc_lect_num'].' </td></tr>
<tr><td>'.$row['pid'].' got '.$row['pc_lect_num'].'</td></tr></tr>';
}
echo "</table>";
It is very basic you can Add more functions to improve the functionality of it.

Related

PHP Getting Data From MySQL [duplicate]

I am a teacher and I have a mysql table called 'gabber' which holds scores of student quizzes. The fields are 'Exercise', 'realname, 'Score', 'Start_Time' and 'End_Time'. If a student completes more than one type of quiz, then this will appear as another row in the table, but of course with a different Exercise value.
My code below, which very nearly works, first finds the unique exercise values, and uses these to print the table column headings. These unique exercise values are also used to create the second query, which finds the minimum (i.e. first attempt) score for each student's attempt at each quiz.
Anyway, the php code works EXCEPT for printing each value twice. i.e. the name is printed twice, as is each score. I know that my query is definitely correct (tested in phpmyadmin), but I think things are going wrong in the nested for loop. I have tried reading about PDOstatement which the query returns, but I could not understand it. I appreciate that there are other posts on stackoverflower about "printing twice", but they could not help me solve this.
Any suggestions on how to make this work would be excellent. Thanks, Matt.
<?
$dbh = new PDO("mysql:host=XXX;dbname=gabber", user, pass);
$query2 = "SELECT realname";
echo '<style>table{border-collapse:collapse;}';
echo 'table, td, th{border:1px solid black;}</style>';
echo '<table><tr><td></td>';
foreach($dbh->query('SELECT DISTINCT Exercise FROM a2_physics') as $row) {
echo '<td>';
echo $row[0];
echo '</td>';
$query2.=', MIN( IF( Exercise = "';
$query2.=$row[0];
$query2.='", Score, NULL ) ) AS "';
$query2.=$row[0];
$query2.='"';
}
echo '</tr>';
$query2=$query2.' FROM a2_physics';
$query2=$query2.' GROUP BY realname';
//echo $query2;
foreach($dbh->query($query2) as $row) {
echo '<tr>';
foreach($row as $element)
{
echo '<td>';
echo $element;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
When connecting to PDO, do it this way
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);

Print MySQL table in PHP without knowing the columns

Im currently making a private "list management" system in which I store SQL queries in the database. So that I can via the front-end create new "lists" (which basicly are sql queries), and view them.
I have made the front end so you can save queries into the database, and im at the point where I want PHP execute and print out the results of one of my queries. This happens when I select one of my stored "lists" on my frontend. So when I press one of the lists, it should execute the SQL query. So far, so good.
But how can I, via PHP, print a table (like the one you get out from phpMyAdmin when viewing the contents of a table) without knowing how many / what columns exists? I want the script to be dynamic, so I can view results of all kinds of SELECT queries (on different tables).
Any tips or pointers?
Rather than using deprecated libraries, use PDO instead.
$db = new PDO($dsn); //$dsn is the database connection strings. Depends on your DB.
//it can be as simple as "odbc:CONN_NAME"
$stmt = $db->prepare("SELECT * FROM $tablename");
//be sure to sanitize $tablename! use a whitelist filter, not escapes!
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); //fetch as associative array
if($rows){
//check if there are actual rows!
$first_row = reset($rows); //Resets the internal pointer, return the first elem.
$header_str = '<th>' . implode('</th><th>', array_keys($first_row)) . '</th>';
$table_body_rows = array();
foreach($rows as $row){
$table_body_rows[] = '<td>' .
implode('</td><td>', $row) .
'</td>';
}
$body_str = '<tr>' . implode('</tr><tr>', $table_body_rows) . '</tr>';
$tbl = "<table><thead><tr>$header_str</tr></thead><tbody>$body_str</tbody></table>";
} else {
//something went wrong
}
show tables is probably what you need
echo "<table><tr>";
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "<td> $row[0] </td>";
}
echo "</tr></table>"
mysql_free_result($result);
If you need to print a row with header (column names), you have to do it this way:
$result=mysql_query("SELECT * FROM yourtable WHERE 1");
if (mysql_num_rows($result)<1) echo "Table is empty";
else
{
$row=mysql_fetch_assoc($result);
echo "<table>";
echo "<tr>";
echo "<th>".join("</th><th>",array_keys($row))."</th>";
echo "</tr>";
while ($row)
{
echo "<tr>";
echo "<td>".join("</td><td>",$row)."</td>";
echo "</tr>";
$row=mysql_fetch_assoc($result);
}
echo "</table>";
}
This is just the basic concept. If your table has values which may contain HTML tags and other stuff, you'll need to apply htmlspecialchars() on all values of $row. This can be done with array_walk(). Furthermore you didn't mention what PHP version are you using and what MySQL API do you prefer. Some people suggested to use mysqli or PDO, that's up to you to rewrite the code according to your preferred API.

What causes a query to exclude first record

PHP and MySQL:What causes a query to exclude the first record in a table:
for example i have a script like this:
$query = "SELECT * FROM cars WHERE car_name = 'BMW'";
$results = mysql_query($query);
echo "<table border='1'>";
echo "<tr>";
echo "<th>Vehicle Name:<th>";
echo "</tr>";
while($row = mysql_fetch_array($result)){
$name = $row['car_name'];
echo "<tr>";
echo "<td>$name<td>";
echo "</tr>";
}
echo "</table>";
All rows are returned except the first one.Please help a brother out folks.
Not an answer, but too long for a comment:
Let's take a peak at your table cars.
What does
$qs = array(
array('total #rows', 'SELECT Count(*) FROM cars'),
array('#BMW', "SELECT Count(*) FROM cars WHERE car_name='BMW'"),
array('#LIKE BMW', "SELECT Count(*) FROM cars WHERE car_name LIKE '%BMW%'"),
array('#car_names', "SELECT Count(*) FROM (SELECT distinct car_name as foo FROM cars) as bar")
);
foreach( $qs as $query ) {
echo $query[0], "<br />\r\n";
$result = mysql_query($query[1]) or die(mysql_error());
while ( false!==($row=mysql_fetch_row($result)) ) {
echo ' ', $row[0], "\r\n";
}
}
print if placed in your script instead of your posted code?
The output should be something like
total #rows<br />
6
#BMW<br />
2
#LIKE BMW<br />
3
#car_names<br />
4
BTW: the mysql_* extension is deprecated,
see http://docs.php.net/manual/en/mysqlinfo.api.choosing.php
EDIT
If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same name,
you must use the numeric index of the column or make an alias for the
column. For aliased columns, you cannot access the contents with the
original column name
You are using mysql_fetch_array and this is what it says in the documentation. I never use mysql* functions so I wouldn't have jumped to this type of conclusion quickly. Use mysql_fetch_assoc($results) and I'm 99% sure it will resolve your issue. The why this would be different is in the paragraph above from the documentation. I assume your first row is identical to at least 1 of the below rows. Which means it is very likely you're missing more than just the first one. May or may not be the case.
END EDIT
Add 4 things to your code.
echo "<tr>";
echo "<th>ID</th>"; // THIS
echo "<th>Vehicle Name:</th>"; // Add closing tags........
echo "</tr>";
echo mysql_num_rows($results); // THIS (compare this to your MYSQL output row count)
while($row = mysql_fetch_array($results)){ **THIS... you have $results set with query, but $result here*** make sure both are $results OR $result
$id = $row['YOUR_AI_ID']; // THIS
$name = $row['car_name'];
echo "<tr>";
echo "<td>$id</td>"; // THIS
echo "<td>$name</td>"; // Add closing tags.......
echo "</tr>";
}
Go go do now. Come back with results.

Results of MYSQL query printed twice using PDO

I am a teacher and I have a mysql table called 'gabber' which holds scores of student quizzes. The fields are 'Exercise', 'realname, 'Score', 'Start_Time' and 'End_Time'. If a student completes more than one type of quiz, then this will appear as another row in the table, but of course with a different Exercise value.
My code below, which very nearly works, first finds the unique exercise values, and uses these to print the table column headings. These unique exercise values are also used to create the second query, which finds the minimum (i.e. first attempt) score for each student's attempt at each quiz.
Anyway, the php code works EXCEPT for printing each value twice. i.e. the name is printed twice, as is each score. I know that my query is definitely correct (tested in phpmyadmin), but I think things are going wrong in the nested for loop. I have tried reading about PDOstatement which the query returns, but I could not understand it. I appreciate that there are other posts on stackoverflower about "printing twice", but they could not help me solve this.
Any suggestions on how to make this work would be excellent. Thanks, Matt.
<?
$dbh = new PDO("mysql:host=XXX;dbname=gabber", user, pass);
$query2 = "SELECT realname";
echo '<style>table{border-collapse:collapse;}';
echo 'table, td, th{border:1px solid black;}</style>';
echo '<table><tr><td></td>';
foreach($dbh->query('SELECT DISTINCT Exercise FROM a2_physics') as $row) {
echo '<td>';
echo $row[0];
echo '</td>';
$query2.=', MIN( IF( Exercise = "';
$query2.=$row[0];
$query2.='", Score, NULL ) ) AS "';
$query2.=$row[0];
$query2.='"';
}
echo '</tr>';
$query2=$query2.' FROM a2_physics';
$query2=$query2.' GROUP BY realname';
//echo $query2;
foreach($dbh->query($query2) as $row) {
echo '<tr>';
foreach($row as $element)
{
echo '<td>';
echo $element;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
When connecting to PDO, do it this way
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);

mysql query giving incorrect result in for loop

The code belows gives me only 18 records
<?php
$result4 = mysql_query("select Distinct Country from trendsmtable where WHORegionAC='Europe - all countries' GROUP BY Country ");
echo "<table width=880 align=center>";
echo "<tr><td colspan=4 style='font-family:Arial;'><b>European Region</b></td></tr>";
$num_columns4 = 4;
$num_rows4 = mysql_num_rows($result4);
$i=0;
while($row4 = mysql_fetch_assoc($result4)){
$results[$i] = $row4['Country'];
$i++;
}
unset($i);
$k=0;
for ($i=0;$i<=($num_rows4/($num_columns4+1));$i++){
echo '<tr>';
for($j=1;$j<=$num_columns4;$j++){
echo "<td width=220 style='font-family:Arial; font-size:12px'>".$results[$k].'</td>';
$k++;
}
echo '</tr>';
$k++;
}
echo "</table>";
?>
while the select statement
select Distinct Country from trendsmtable where WHORegionAC='Europe -
all countries'
returns 22 rows while I execute it in mysql which is correct!
Please help me to found the error.
Well, you have an extra $k++ in there that you don't need:
$k++; // keep this one
}
echo '</tr>';
$k++; // remove this one
}
Edit
I've gone through your code and I've made some edits. Hopefully they'll clean your issue along the way:
// got rid of group by. With a select distinct, it isn't necessary
$result4 = mysql_query("select Distinct Country from trendsmtable where ".
"WHORegionAC='Europe - all countries'");
// a good practice is to always double-quote your HTML attributes.
echo "<table width=\"880\" align=\"center\">";
echo "<tr><td colspan=4 style=\"font-family:Arial;\">".
"<b>European Region</b></td></tr>";
$num_columns4 = 4; // where does 4 come from.
// $results was never initialized before.
$results = array();
while($row4 = mysql_fetch_assoc($result4)){
// This is generally thought of as "cleaner" than using an index.
// And since there cannot be more than, say, 220 rows, cleanliness
// should be a high-priority standard.
$results[] = $row4['Country'];
}
// mysql_num_rows rarely provides any major benefit at all.
$num_rows4 = count($results);
foreach( $results as $key => $val )
{
// This happens every time we fill all columns and need a new row.
if( !( $key % $num_columns4 ) )
{
// makes it so that after the first time this closes the prev
// row before starting a new one.
if( $key ) echo '</tr>';
echo '<tr>';
}
// insert nag about CSS
echo '<td width="220" style="font-family:Arial; font-size:12px">'.
$val.
'</td>';
}
echo '</tr></table>';
I think the PHP looks a little odd, it looks like you are looping from 0 to (22 / 5)
then in the inner loop 4 times.
The group by should not make any difference as you are doing a select distinct
Your SQL code in the PHP file contains a GROUP BY clause, which can reduce the number of rows returned, if you have a country more than once in the db.

Categories