My $num_rows echos the total row count but I want the current row number.
<?php
$result = mysql_query('SELECT * FROM texts ORDER BY id desc');
while($row = mysql_fetch_array($result)){
$num_rows = mysql_num_rows($result);
?>
<tr class="alt">
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['title']; ?></td>
<td>Original</td>
<td>#English</td>
<td><?php echo $num_rows; ?></td>
</tr>
<?php
}
?>
Thank you :)
why you should not use a increment variable to count the loop turns inside while?
$tmpCount = 1;
while() {
$tmpCount ++;
}
Is this helpful to you? or are you expecting the physical row number of from database?
If you want to just number the rows returned by the query (instead of using the actual ID - $row['id'] presumably), you can just increment a number with each row:
$num_rows = 0;
while ($row = mysql_fetch_array($result)){
$num_rows++;
// ...
This works, but when sorting, the number gets locked in and doesn't return to the natural sort. The initial sort will be 1, 2, 3 but when clicking on the column to sort, whatever row is associated with the first sort will stay with it and the new sort will not have the num_rows in order!
Related
I currently can print 8 records in one column, I am trying to print 16 records in 2 columns of 8 or 24 in 3 columns of 8. After several months of trying I have to admit it baffles me. Any help or guidance would be greatly appreciated. My code below gives me the first column of 8 perfectly, but after that I am stuck
$result1 = $db->prepare("SELECT * FROM table WHERE id='100' ORDER BY id ASC LIMIT 8 ");
$result1->execute();
print("");
$count = $result1->rowCount();
print("");
for($i=0; $row = $result1->fetch(); $i++) {
?>
<body topmargin="0">
<table border="0">
<tr>
<td>
<font size="5">ID:<?php echo $row['id']; ?></font><br>
<font size="5"><?php echo $row['field1']; ?></font><br>
<font size="5">Field1<?php echo $row['field2']; ?></font><br>
<font size="4">Field2<?php echo $row['field3']; ?></font><br>
<font size="3">Field3<?php echo $row['field4']; ?></font><br>
</td>
</tr>
<?php
}
?>
I would approach this by making a loop to output a table with a desired column count.
Within that you will need to iterate a number of rows, and then inside that loop, write out the table entry for each of the columns.
If your data doesn't exactly fill columns x rows then you'll get some blank items of course.
$rows = ceil($count / $columns)
for ($r = 0; $r < $rows; $r++) {
echo "<tr>";
for ($c = 0; $c < $columns; $c++) {
$value = $result1->getNext() ?? '';
echo "<td>{$value}</td>";
}
echo "</tr>";
}
The getNext() here is up to you of how best to implement. You could load all the values into an array and increment an index counter, or your $db class may give you a more helpful accessor for getting the next value.
I'm creating a webpage that lists ten characters in a game based on their experience levels and displays them with a picture associated each character. My code works, but the output is in a column when I'd like it to be in a row. I did see where something very similar had been asked here: MySQL data from database align horizontally and I tried to follow that example but either ended up with errors or the faces didn't appear. I'm a hobbyist, I'm just doing this for friends, so my knowledge is pretty basic.
Relevant code:
<table border="3" width="90%">
<tr>
<th width="25%">XP</th>
<td>
<?php
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<left>";
echo "<table border='1'>";
echo "<tr><td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td></tr>";
echo "</table>";
echo "<br>";
}
?>
</td>
</tr>
</table>
Anyone got any suggestions? Thanks!
So after following Bombelman's suggestion below, I got it to work. In case anyone else runs into this problem, here is the working code:
<tr>
<th width="25%">Goody Two Shoes</th>
<td><?php
echo "<table border='1'><tr>";
echo "<left>";
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
?></td>
</tr>
place the "table" and "row" tag out of the loop, and have the results in between the "td" tags looped only.
Looking at your script, you have several tables.
Make sure only the < td > and < /td > tags are within the while-loop.
The output should be similar to my example.
Hope it helps !
<table style="width:100%">
<tr>
<td>Character 1</td>
<td>Character 2</td>
<td>Character 3</td>
<td>Character 4</td>
<td>Character 5</td>
</tr>
</table>
Looking at the sql queries makes me think you ought to be able to do a basic join upon the two tables rather than having nested queries within a loop. The generation of the html table should be fairly straightforward - iterate through the recordset results for rows in the table and iterate through the fields returned by the query for individual cells within the table row.
$sql='select l.*, d.face from `life` l
join `description` d on d.`charname`=l.`charname`
where l.`goodxp` > 0
order by l.`goodxp` desc
limit 10';
$res=$con->query( $sql );
/* fetch the column names into an array */
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
$html=array();
$html[]='<table>';
/* add field names as column headers */
$html[]='<tr>';
foreach( $fields as $field )$html[]='<th>'.$field.'</th>';
$html[]='</tr>';
/*
iterate through recordset,
add new row for every record
but table cell for every
field in record
*/
while( $rs=$res->fetch_object() ){
$html[]='<tr>';
foreach( $fields as $field ){/* show image or text */
$data = $field=='face' ? "<img src='pictures/{$rs->$field}' />" : $rs->$field;
$html[]='<td>'.$data.'</td>';
}
$html[]='</tr>';
}
$html[]='</table>';
/* render table */
echo implode( PHP_EOL, $html );
Depending upon the version of PHP you may get nagged at when using the array_walk function and passing the third argument by reference. If that is the case then change
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
for
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key ){
global $fields;
$fields[]=$item->name;
} );
I am fetching data in php from mysql table. Let say I retrieved 15 rows containing 15 unique ids. Now I want to get the the very first fetched id from the results.
This is what I'm trying..but its giving me the last id
<?php
$results = $db->query("SELECT * FROM orders where Sales_Rep='$sales_rep'");
while($row = $results->fetch_assoc()){
?>
<tr>
<td><?php echo $row["Order_ID"] ?></td>
<td><?php echo $row["Company_Name"]?></td>
</tr>
<?php
$last_order_date= $row["Order_ID"];
echo $last_order_date;
} //end of while loop
?>
you could simply add index like this
$i = 0;
while loop
$i++;
if($i === 1)
{get ID}
//rest of your while loop
endwhile;
you can modify your sql to
SELECT * FROM orders where Sales_Rep='$sales_rep' Order By Order_ID DESC
or you use this code
<?php
$results = $db->query("SELECT * FROM orders where Sales_Rep='$sales_rep'");
$i =0;
$first_id = 0;
while($row = $results->fetch_assoc()){
if ($i===0){
$first_id = $row["Order_ID"];}
$i++;
?>
<tr>
<td><?php echo $row["Order_ID"] ?></td>
<td><?php echo $row["Company_Name"]?></td>
</tr>
<?php
$last_order_date= $row["Order_ID"];
echo $last_order_date;
} //end of while loop
?>
your first Id is in $first_id
That loop using do while, and it is working fine but when I add another do while in to this the second do while work but first do while only show one row not all 10 row. My code is below
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<?php do { ?>
<td><?php echo $row_Recordset1['nav']; ?></td>
<?php } while ($row_Recordset1= mysql_fetch_assoc($Recordset1)); ?>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
My date should be displayed once in a row but all the other td will be took from nav;
This is what I want:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
|2014-02-25|3.1|1.2|1.5|
But I'm currently getting:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
You should look at http://php.net/mysql_fetch_assoc
It moves the internal pointer one step ahead, so each time you do mysql_fetch_assoc() you get the next value, hence only your enternal do while is executed. That is, only date from the first row is output, and all other values are output in second do while;
Try this for exercise:
$q = mysql_query("SOME MYSQL QUERY WITH MINIMUM THREE ROWS");
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
print_r($f);
First of all, please don't bounce in and out of PHP like that...
<?php
do {
echo '<tr>
<td>';
echo $row_Recordset1['date'];
echo '</td>';
do {
echo '<td>';
echo $row_Recordset1['nav'];
echo '</td>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
echo '</tr>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
?>
Where do you fetch your first $row_Recordset1? Somewhere earlier than this code? You're going to output table cells (<td>) until you run out of rows. I don't think you want that.
Like so:
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<td><?php echo $row_Recordset1['nav']; ?></td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Because each time you use mysql_fetch_assoc it does the following
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
Part of the reason this doesn't work is because you are re-assigning the value of the same variable. If you don't want to lose it then you cannot do it this way. At the very least it is a bad idea if you ever intend to do anything new with the code.
Next, I really recommend you populate an array with the data first before you ever do anything with outputting it. It is a very good idea to separate logic from output.
Your code should look more like this:
<?php
//Assumes you have already connected to a mysqli resource
$conditional_data_filtered = $mysqli->real_escape_string($conditional_data);
$sql = "SELECT date, nav FROM some_table WHERE some_column = '" . $conditional_data_filtered . "'";
if ($result = $mysqli->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$data = array(); //Make sure we start with a fresh array each time.
$data['date'] = $row['date'];
//Now I think you have a bunch of data in the nav you need to loop through
$nav_filtered = $mysqli->real_escape_string($row['nav']);
$subSql = "SELECT some_data FROM navigation WHERE some_identifier = '" . $nav_filtered . "'";
if ($subResult = $mysqli->query($subSql)) {
while ($subRow = $subResult->fetch_assoc()) {
$data['nav'][] = $subRow;
}
}
$rowList[] = $data;
}
/* free result set */
$result->free();
}
foreach ($rowList as $rowData) {
echo "<tr>";
echo "<td>" . $rowData['date'] . "</td>";
foreach ($rowData['nav'] as $navData) {
echo "<td>" . $navData['some_info'] . "</td>";
}
echo "</tr>";
}
?>
Just a note: If you really don't have sub-data and just want to output the next column then you don't need a sub-loop. You just need to echo the contents of the column like you did with the first one. Then you can get rid of the sub-loops I have shown above and just put it within the first loop.
I am trying to create a webpage that does a simple query of a table and displays the table to a page, but with one complex twist that has got me confused. Here are the column names and one example record from the table separated by commas:
R_ID , B_ID , R_No , RoomName , showers , eyewashPlumbed , EyewashBottles
1 , 609 , 609 , Hazardous Waste Shed , 1 , 1 , 1
I need to print each row of this table, but also print multiple rows if either showers, eyewashPlumbed, or EyewashBottles is greater than 0. For example, I would print this row three times. If showers was 0 I would only print it two times (one for eyewashPlumbed, one for EyewashBottles, and 0 for showers). If showers was 2 I would print it 4 times, etc.
The code I'm using to print is as follows:
<?php while ($row = mysql_fetch_array($result, MYSQL_ASSOC)): ?>
<tr>
<td><?php print $row["B_ID"];?></td>
<td><?php print $row["R_No"];?></td>
<td><?php print $row["RoomName"];?></td>
<td><?php print $row["Showers"];?></td>
<td><?php print $row["eyewashPlumbed"];?></td>
<td><?php print $row["EyewashBottles"];?></td>
</tr>
<?php endwhile; ?>
The problem is that I don't know how to interrupt the while loop in order to print the same row multiple times. It goes onto the next row as it pulls from the mysql_fetch_array.
You really should switch to PDO / mysqli, but with your current code it would be something like (for showers as in your example):
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)):
$count = 2 + $row["showers"];
for ($i = 0; $i < $count)
{
?>
<tr>
<td><?php print $row["Date"];?></td>
<td><?php print $row["Inspector1"];?></td>
<td><?php print $row["Inspector2"];?></td>
<td><?php print $row["Building_Name"];?></td>
<td><?php print $row["Room"];?></td>
<td><?php print ($i + 1);?></td>
</tr>
<?php
}
endwhile;
?>
You probably want to change $row["shower_no"] to something like $i + 1 as that column does not appear in your database.
If you have a variety of rules
I would handle this problem like this:
<?php
function printRow($row=array(), $times=1) {
for($i=0; $i<$times; $i++) {
echo "
<tr>
<td>{$row["Date"]}</td>
<td>{$row["Inspector1"]}</td>
<td>{$row["Inspector2"]}</td>
<td>{$row["Building_Name"]}</td>
<td>{$row["Room"]}</td>
<td>{$row["shower_no"]}</td>
</tr>
";
}
}
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
switch(true) {
case ($row['eyewashPlumbed']>0 or $row['EyewashBottles']>0):
printRow($row, 3); // print 3 times
break;
case ($row['showers']==0): // print 2 times
printRow($row, 2);
break;
default: // default print 1 time only
printRow($row, 1);
}
}
?>