I am newbie and need help to resolve my issue.
extract row values without loop.
Table:
----------------
YEAR | SALES
----------------
2011 | 45
2012 | 34
2013 | 23
2014 | 10
2015 | 48
----------------
PHP code:
$sql = "SELECT YEAR FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "YEAR: " . $row["YEAR"]. "<br>";
}
} else {
echo "0 results";
}
looking for solution to output the year value without loop , something similar below
while loop prints all row values , but would like to extract individual year value from query and assign it to a variable
$year1 = $row["YEAR"]
$year2 = $row["YEAR"]
$year3 = $row["YEAR"]
with your current code
$i=1;
while($row = $result->fetch_assoc()) {
${'year'.$i}= $row["YEAR"];
$i++;
//echo "YEAR: " . $row["YEAR"]. "<br>";
}
now you can access $year1; $year2 and so on
Related
How to create a table with data retrieved from MySQL with PHP
-------------------------
| albumID | trackID |
-------------------------
| | 1990 |
- 1 -------------
| | 1991 |
-------------------------
| | 1992 |
- -------------
| 2 | 1993 |
- -------------
| | 1994 |
-------------------------
I can generate a table from the database, but the result will be only like each result in one row
$query = "SELECT albumID, trackID
FROM songs";
$result = mysqli_query($db, $query);
echo "<table>";
echo "<tr>\n";
echo "<th>albumID</th>\n";
echo "<th>trackID</th>\n";
echo "</tr>\n";
while ($data = mysqli_fetch_array($result)) {
echo "<tr>\n";
echo "<td>$data[0]</td>\n";
echo "<td>$data[1]</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
Any help given is really appreciated!
You can do this by using a variable to keep track of the current album and only output the album once as shown below.
$current_album = ''; # initialize tracking var
while ($data = mysqli_fetch_array($result)) {
echo "<tr>\n";
if ($current_album != $data[0]) {
echo "<td>$data[0]</td>\n";
$current_album = $data[0];
} else {
echo "<td> </td>\n"; # insert empty cell
}
echo "<td>$data[1]</td>\n";
echo "</tr>\n";
}
This will have the album ID appearing in the first row for the album. If you want it to be vertically centered you can use rowspan on the td element, but in order to know how many rows each album has you will either need to update your sql query to return that or you can process the results into a multidimensional array and then loop through that to generate the output.
Maybe not the most elegant solution, but should do the trick.
$query = "select albumID as album, group_concat(trackID) as tracks from songs group by albumID";
$result = mysqli_query($db, $query);
echo "<table>";
echo "<tr>\n";
echo "<th>albumID</th>\n";
echo "<th>trackID</th>\n";
echo "</tr>\n";
while ($data = mysqli_fetch_array($result)) {
$tracks = explode(",", $data[1]);
echo "<tr>\n";
echo "<td rowspan=\"".count($tracks)."\">$data[0]</td>\n";
foreach ($tracks as $key => $value) {
echo "<td>$value</td>\n"
}
echo "</tr>\n";
}
echo "</table>\n";
Edit your query to return the numbers of tracks of the album and use that number to create a rowspan only on the first track row. I wrote a little example but I havn't tried if it works.
$query = "SELECT s.albumID, s.trackID,
( SELECT COUNT(*)
FROM songs s2
WHERE s2.albumID = s.albumID )
FROM songs s";
$result = mysqli_query($db, $query);
echo "<table>";
echo "<tr>\n";
echo "<th>albumID</th>\n";
echo "<th>trackID</th>\n";
echo "</tr>\n";
$tmpAlbum = '';
while ($data = mysqli_fetch_array($result)) {
echo "<tr>\n";
echo "<td";
if($data[2] == 1){
echo "<td>$data[0]</td>\n";
}else{
if($data[0] != $tmpAlbum){
echo "<td rowspan=\"".$data[2]."\">$data[0]</td>\n";
}
}
$tmpAlbum = $data[0];
echo "<td>$data[1]</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
I have this table:
img id | img_path | listing_assoc_id|
----------------------------------------
11 |img/img1.jpg | 12 |
12 |img/img2.jpg | 12 |
13 |img/img3.jpg | 12 |
14 |img/img4.jpg | 12 |
15 |img/img5.jpg | 12 |
16 |img/img6.jpg | 12 |
18 |img/img7.jpg | 12 |
21 |img/img8.jpg | 12 |
22 |img/img9.jpg | 12 |
23 |img/img10.jpg| 12 |
24 |img/img11.jpg| 12 |
And I want to display it into a table in html
like this maximum of 5 images per row. I have been fiddling with different loops in combination of different loops like above for a couple hours but haven't found one that works like I need. They are either displaying the same images across the entire row or are messed up in some other way. Obviously need to use tr & td elements to format table correctly.
What I need:
<tr>
<td>img1</td> <td>img2</td> <td>img3</td> <td>img4</td> <td>img5</td>
</tr>
<tr>
<td>img6</td> <td>img7</td> <td>img8</td> <td>img9</td> <td>img10</td>
</tr>
<tr>
<td>img11</td>
</tr>
Some of the code that doesn't work:
$query = "SELECT * FROM listings_gallery WHERE listing_assoc_id = " 12 " ORDER BY img_id ASC";
$image_set = mysqli_query($connection, $query);
echo '<tr>';
while($img = mysqli_fetch_assoc($image_set)){
while($img['img_id'] < 5){
echo "<td><img src='" . $img['img_path'] . "'></td>";
}
echo '<tr>';
}
I wouldn't actually depend on the image ID. You could use % 5 to do this, but the IDs may be out of order, etc. Instead, you can just fetch everything into an array and use array_chunk
$img = array();
while ($img = mysqli_fetch_assoc($image_set)) {
$imgs[] = $img;
}
foreach (array_chunk($imgs, 5) as $img_chunk) {
echo "<tr>";
foreach ($img_chunk as $img) {
echo "<td>$img</td>";
}
echo "</tr>";
}
This is probably about as simple as it gets but it's not as memory efficient as could be. You could also maintain your own counter and check % 5 for that to break out of the inner loop.
$images_rows = mysqli_query($connection, $query);
$images = array();
while ($image = mysqli_fetch_assoc($images_rows)) {
$images[] = $image;
}
echo '<table><tr>';
$ct = 0;
$ctt = 0;
$size = sizeOf($images) - 1;
foreach($images as $image){
if($ct == 5) {
echo '<tr>';
$ct = 0;
}
echo "<td><img src='" . $image['img_path'] . "'></td>";
$ct++;
$ctt++;
echo ($ct == 5 && $ctt != $size) ? '</tr>': '';
}
echo '</tr></table>'
How can i display variable only once in the table.
<?php
$sql = mysql_query("SELECT * FROM babydata");
while ($row = mysql_fetch_array($sql)) {
for ($i = 1; $i <= 72; $i++) {
if ($i == $weeknumber) {
echo "<tr><td width='40'>Week $i</td>";
echo "<td width='500' >" . count($row[$menucompare]) . "</td></tr>";
}
}
}
?>
this code display like this:
--------------
week4 | 1
-------------
week4 | 1
-------------
But i want to display weeknumber only once and count($row[$menucompare]) will be counted 2 in week 4 . not 1 and 1 .
Like this:
--------------
week4 | 2
---------------
Seems like you want to output the amount of tuples in babydata for a certain week. You can just filter out any tuples which dont belohnt to the $weeknumber in your query.
// TODO: Assert, that $weeknumber is an integer, to not be prune to SQL injection.
$weeknumber = (int)(($currentdate - $birthday) / (7 * 24 * 60 * 60)) + 1;
// Select the amount of tuples in babydata for the desired $weeknumber.
$result = mysql_query("SELECT count(*) FROM babydata ".
"WHERE week = $weeknumber");
// There is only one tuple with one column that contains the amount as number.
$row = mysql_fetch_row($result);
// Output the week and the amount of data.
echo "<tr><td width='40'>Week $weeknumber</td>" ;
echo "<td width='500' >".$row[0]."</td></tr>";
No need for loops.
To output all weeks and their respective amount of data:
// Select the amount of tuples in babydata for all weeks.
$result = mysql_query("SELECT week, count(*) FROM babydata ".
"GROUP BY week");
// For all weeks:
while ($row = mysql_fetch_row($result))
{
// Output the week and the amount of data.
echo "<tr><td width='40'>Week ".$row[0]."</td>" ;
echo "<td width='500' >".$row[1]."</td></tr>";
}
This assumes that you have a column week in your table babydata that contains just a number. This outputs only weeks, that have at least one tuple.
You can do that directly in the SQL. Warning: I didn't actually tested this.
SELECT week, count(week) FROM babydata GROUP BY week;
This will directly return a result like
--------------
week4 | 2
week5 | 3
--------------
Just replace week with the actual name of your week field, and adapt the PHP to handle the new result structure. Something along these lines:
$sql= mysql_query("SELECT * FROM babydata");
while($row = mysql_fetch_array($sql))
{
echo "<tr><td width='40'>Week ".$row[0]."</td>" ;
echo "<td width='500' >".$row[1]."</td></tr>";
}
I am trying to print a recursive list where every date has a sublist of events ordered by date.
For example on the database I have:
+------+----------+--------+
| date | event_id | post_id|
+------+----------+--------+
|date1 | event1 | post1 |
|date1 | event2 | post2 |
|date1 | event3 | post3 |
|date2 | event4 | post4 |
|date2 | event5 | post5 |
+------+----------+--------+
I need to print
<ul>
<li>date1</li>
<ul>
<li>event1, post1</li>
<li>event2, post2</li>
<li>event3, post3</li>
</ul>
<li>Date 2</li>
<ul>
<li>event4, post4</li>
<li>event5, post5</li>
</ul>
</ul>
how can I print in php the
select date, event_id, post_id from tablename
query in php to have this?
After a while with php and mysql, I do the least I can in mysql, even if it's often more elegant. Performance of mysql is crap. And even if what you query is fast, it can still slow down another query elsewhere done by another user. So here is a response with the least load on the DB. One query, no grouping. just select your 3 fields, and you can apply this.
$lastDate = null; // lastDate will be updated at each row, so we can check if it has changed the next one.
echo '<ul>';
foreach ($queryResult as $row)
{
if ( $lastDate != $row['date'] )
{
if ( $lastDate) { echo '</ul>'; } // if lastdate "exists", it's not the first, so let't close the "date" list...
echo '<li>', $row['date'], '</li><ul>'; // ... and start a new one
}
echo '<li>', $row['event_id'], ', ',$row['post_id'], '</li>';
$lastDate = $row['date'];
}
echo '</ul>'; // close the very last date list
echo '</ul>'; // close the the full list
It looks like you need MySQL GROUP_CONCAT().
SELECT date,
GROUP_CONCAT(event_id) AS 'event_ids',
GROUP_CONCAT(post_id) AS 'post_ids'
FROM tablename
GROUP BY date
This will return results with three fields. date will be the date field, event_ids and post_ids will be comma separated lists of the events and posts that fall under that date.
This should work. You'd want to add some error checking though.
<ul>
<?php
$result = mysql_query(SELECT date FROM tableName);
if (mysql_num_rows($result) > 0)
{
while ($dateRow = mysql_fetch_array($result))
{
echo "<li>" . $dateRow['date'] . "</li>";
$result2 = mysql_query("SELECT event_id,post_id FROM tableName where date = '" . $dateRow['date'] . "'");
if (mysql_num_row($result2) > 0)
{
echo "<ul>";
while ($row = mysql_fetch_array($result2))
{
echo "<li>" . $row['event_id'] . " , " . $row['post_id'] . "</li>";
}
echo "</ul>";
}
}
}
?>
</ul>
The following is a rough answer:
$query = "select date, event_id, post_id from tablename order by date";
$result = mysql_query($query);
$currentDate = null;
echo "<ul>";
while($row = mysql_fetch_assoc($result)){
if($currentDate != $row['date']){
echo "<li>" . $currentDate . "</li>";
echo "<ul>";
}
echo "<li>" . $row['event'] . $row['post'] . "</li>";
if($currentDate != $row['date']){
$currentDate = $row['date'];
echo "</ul>";
}
}
echo "</ul>";
Here's my take on the problem. First of all, you should nest the unordered list items into parent elements. The resulting output should be
<ul>
<li>date1
<ul>
<li>event1, post1</li>
<li>event2, post2</li>
<li>event3, post3</li>
</ul>
</li>
<li>Date 2
<ul>
<li>event4, post4</li>
<li>event5, post5</li>
</ul>
</li>
</ul>
Advantages of this nested schema:
valid html (this alone is good enough)
easier DOM-manipulation by Javascript
Here's a function which in theory should output the former html:
function printList()
{
$sql = 'SELECT t.event_id, t.post_id, t.date FROM table t ORDER BY date';
$result = mysql_query($sql);
$date = null;
$out = '';
while($row = mysql_fetch_assoc($result))
{
if($date !== $row['date'])
{
if(!is_null($date))
{
$out .= '</ul></li>';
}
$date = $row['date'];
$out .= sprintf('<li>%s<ul>', $row['date']);
}
$out.= sprintf('<li>%s, %s</li>', $row['event_id'], $row['post_id']);
}
return sprintf('<ul>%s</ul></li></ul>', $out);
}
$sql = "SELECT date, event_id, post_id
FROM tablename
GROUP BY date ORDER BY date";
Table has the following info:
date |vendor|sales|percent|
--------------------------
2009-03-03| 10 |13.50| 1.30 |
2009-03-10| 10 |42.50| 4.25 |
2009-03-03| 21 |23.50| 2.30 |
2009-03-10| 21 |32.50| 3.25 |
2009-03-03| 18 |53.50| 5.30 |
2009-03-10| 18 |44.50| 4.45 |
I want it to sort into separate tables depending on date as follows:
date |vendor|sales|percent|
--------------------------
2009-03-03| 10 |13.50| 1.30 |
2009-03-03| 18 |53.50| 5.30 |
2009-03-03| 21 |23.50| 2.30 |
date |vendor|sales|percent|
--------------------------
2009-03-10| 10 |42.50| 4.25 |
2009-03-10| 18 |44.50| 4.45 |
2009-03-10| 21 |32.50| 3.25 |
I can get this done but I cannot get it to give me the totals for each separate table like:
date |vendor|sales|percent|
--------------------------
2009-03-03| 10 |13.50| 1.30 |
2009-03-03| 18 |53.50| 5.30 |
2009-03-03| 21 |23.50| 2.30 |
Total Sales for 2009-03-03 = $90.50
Total percent for 2009-03-03 = $8.90
date |vendor|sales|percent|
--------------------------
2009-03-10| 10 |42.50| 4.25 |
2009-03-10| 18 |44.50| 4.45 |
2009-03-10| 21 |32.50| 3.25 |
Total Sales for 2009-03-03 = $119.50
Total percent for 2009-03-03 = $11.95
I can get the totals for all but not for individual tables.
Here is my code:
<?php
$con = mysql_connect("localhost", $dbUser, $dbPassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("beans", $con);
$result = mysql_query("SELECT * FROM Deposits WHERE market = '4' ORDER BY eventdate, vendor ASC") or die(mysql_error());
$dateChk = 0;
while($row = mysql_fetch_array($result))
{
$date = $row["eventdate"];
$liclass = $row["vendor"];
$url = $row["trxid"];
$amountdep = $row["amount"];
$depcheck = $row["checkno"];
$deposit_Total = $deposit_Total + $amountdep;
$deposit_3Total = $deposit_3Total + $depcheck;
$deposit_3 = $amountdep / 100;
$dep_percent = $deposit_3 * 3;
$depper_Total = $depper_Total + $dep_percent;
$week = date("W", db_date_to_timestamp($date));
$year = date("Y", db_date_to_timestamp($date));
If($dateChk != $week)
{
echo "<table class=\"adverts\" width=\%100\" cellpadding=\"4\">\n";
echo "<tr><th>Date</th><th>Vendor</th><th>Total Sales</th><th>3% Due</th><th>Week</th></tr>\n";
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
$dateChk = $week;
}
echo "</table>\n";
echo "<p><b>Total reported Market Sales are $ " . $deposit_Total . "</b></p>\n";
echo "<p><b>3 percent of Total reported Market Sales are $ " . $deposit_3Total . "</b></p>\n";
?>
(EDIT: sorry when I posted I saw that you need it in the query!)
$dateChk = 0;
$firstRow = 1;
while($row = mysql_fetch_array($result))
{
$date = $row["eventdate"];
$liclass = $row["vendor"];
$url = $row["trxid"];
$amountdep = $row["amount"];
$depcheck = $row["checkno"];
$deposit_Total = $deposit_Total + $amountdep;
$deposit_3Total = $deposit_3Total + $depcheck;
$deposit_3 = $amountdep / 100;
$dep_percent = $deposit_3 * 3;
$depper_Total = $depper_Total + $dep_percent;
$week = date("W", db_date_to_timestamp($date));
$year = date("Y", db_date_to_timestamp($date));
If($dateChk != $week)
{
if($firstRow == 0)
{
echo "</table>\n";
echo "<p><b>Total reported Market Sales are $ " . $deposit_week_Total . "</b></p>\n";
echo "<p><b>3 percent of Total reported Market Sales are $ " . $deposit_week_3Total . "</b></p>\n";
$deposit_week_Total = 0;
$deposit_week_3Total = 0;
}else
{
$firstRow = 0;
}
echo "<table class=\"adverts\" width=\%100\" cellpadding=\"4\">\n";
echo "<tr><th>Date</th><th>Vendor</th><th>Total Sales</th><th>3% Due</th><th>Week</th></tr>\n";
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>$date</td>\n";
echo "<td>$liclass</td>\n";
echo "<td>$ $amountdep</td>\n";
echo "<td>$ $depcheck</td>\n";
echo "<td>$week</td>\n";
echo "</tr>";
}
$dateChk = $week;
$deposit_week_Total = $deposit_week_Total + $amountdep;
$deposit_week_3Total = $deposit_week_3Total + $depcheck;
}
echo "</table>\n";
echo "<p><b>Total reported Market Sales are $ " . $deposit_Total . "</b></p>\n";
echo "<p><b>3 percent of Total reported Market Sales are $ " . $deposit_3Total . "</b></p>\n";
?>
SQL
"SELECT date, SUM(sales) FROM Deposits WHERE market = '4' GROUP BY date"
Istead of sum(sales) you have to use your own calculations. I suggest to put them into a model.
Would this help?
http://www.plus2net.com/sql_tutorial/sql_sum.php
SELECT SUM (sales) FROM `table_name` WHERE `date` = '$date_you_want'
From my below comment:
SELECT SUM (sales) FROM `table_name` WHERE `date` <= '$start_date_of_week' AND `date` >= '$end_date_of_week'
So basically WHERE date is less than and greater than the two dates that describe the start and stop of the week you want...
Or... I think you could also add the days to the value in the mysql
SELECT SUM (sales) FROM table_name WHERE date LIKE '$yyyy-mm-dd %' ...DATE_ADD code for adding days.. or INTERVAL.
You can get those sums straight by using GROUP BY WITH ROLLUP.