Reputation: 1
I have this mysql table with the following rows:
id_cont suma_lun month year
--------------------------------------------
FL28 2133 March 2012
FL28 2144 April 2012
FL28 2155 May 2012
FL28 2166 June 2012
How can i extract suma_lun, month and year foreach id_cont? so that i get an output like this:
ID: Month: Monthly Sum: Year:
----------------------------------------------
FL28 March 2133 2012
April 2144 2012
May 2155 2012
June 2166 2012
This is my current code:
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) die ('Could not connect to database: '.mysql_error());
mysql_select_db(DB_DATABASE,$link);
$sql="SELECT * FROM test WHERE id_cont = '$cur'";
$result=mysql_query($sql);
while ($row=mysql_fetch_array($result)) {
$a=$row["id_cont"];
$b=$row["suma_lun"];
$c=$row["month"];
$d=$row["year"];
}
I echo the data in a table Thanks!
Upvotes: 0
Views: 265
Reputation: 4601
Use query
SELECT
id_cont, month, suma_lun, year
FROM
`your_table`
ORDER BY
id_cont
Your output will be
id_cont suma_lun month year
--------------------------------------------
FL28 2133 March 2012
FL28 2144 April 2012
FL28 2155 May 2012
FL29 2166 June 2012
FL29 2226 July 2012
FL29 2353 Aug 2012
then in PHP you can get desired output
<?php
$id=0;
while($row=mysql_fetch_array($records))
{
if($row['id_cont']) !=id)
{
echo" $row[id_cont] ";
id=$row['id_cont'];
}
echo "$row[month]";
echo "$row[suma_lun]";
echo "$row[year]";
}
?>
Upvotes: 1
Reputation: 1984
Actually the first recordset is fine. However if you want to get ready-to-display representation straight from DB, try something like this:
SELECT
`id_cont` AS `ID`,
GROUP_CONCAT(`month` SEPARATOR '<br />') AS `Month`,
GROUP_CONCAT(`suma_lun` SEPARATOR '<br />') AS `Monthly Sum`,
GROUP_CONCAT(`year` SEPARATOR '<br />') AS `Year`
FROM
`your_table`
GROUP BY
`id_cont`
Upvotes: 0
Reputation: 33391
If you want to find all the months, suma_luns and years for each id_cont
:
Since you didn't give a name for your table, I will be using "cont_table" as the table name:
SELECT month as id_cont as ID, month, suma_lun as Monthly_Sum, year FROM cont_table WHERE id_cont = 'FL28';
Then you would run this query varying id_cont = ?
to get the records for the IDs you require.
Use mysql_fetch_assoc to fetch the results into an associative array using a while loop to get your data using $result[column]
.
For example, the Month in the first row would be: $result['month']
in the first iteration of your loop.
Upvotes: 0