do while in do while in php - php

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.

Related

PHP While HTML Table

I am trying to get my code to display in an HTML table using the while loop. However, I can't get my table to display. Is there something wrong with the way I am trying to echo the table out?
<?php
#-----call includes-----# include('E:/includes/database.php');
include('E:/includes/sendmail.php');
ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors','on');
$do = $_REQUEST['do'];
$queryOrders = "select t2.SlpName As 'Seller', t1.SWW As 'Vendor', t0.DocDate As 'Date',t0.DocTotal As 'Total'
from twh.dbo.OINV t0
inner join twh.dbo.inv1 t1 on t0.DocEntry = t1.DocEntry
inner join twh.dbo.OSLP t2 on t1.SlpCode = t2.SlpCode
where t0.DocDate > DATEADD (month, -2, getdate())
order by t0.DocTotal desc";
$resultItemData = sqlsrv_query($con, $queryOrders);
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Seller</th>";
echo "<th>Vendor</th>";
echo "<th>Date</th>";
echo "<th>Total</th></tr>"
while($rowItemData = sqlsrv_fetch_array($resultItemData)){
echo "<tr><td>";
echo "$resultItemData";
echo "</td></tr>";
endwhile;
}
echo"</table>";
Modified a little bit. Check this:
while($rowItemData = sqlsrv_fetch_array($resultItemData)) :
echo "<tr><td>";
echo $rowItemData[ColumnValue]; //In your code, didn't access the column value earlier
echo "</td></tr>";
endwhile;
There's a combination of problems at play:
First, you open the while with {, but close with endwhile; - while technically not a problem, it's not consistent - if you open with {, it's best practice to close with }.
Second, you're attempting to echo an entire array, which won't work properly.
Third, no need to put the value inside of quotes: echo "$resultItemData"; could simply be echo $resultItemData.
Fourth, you're attempting to echo $resultItemData, which is a resource, not the row data. You want to echo $rowItemData values.
And finally, you'll likely want the results in an associative array, rather than a numerically-indexed array, so you might consider using sqlsrv_fetch_array( $resultItemData, SQLSRV_FETCH_ASSOC).
Below is your code, revised to work, and follow a bit better practices:
// columns: 'Seller',Vendor, 'Date', 'Total'
while( $rowItemData = sqlsrv_fetch_array( $resultItemData, SQLSRV_FETCH_ASSOC ) ) {
echo "<tr><td>";
echo "<td>$rowItemData['Seller']</td>";
echo "<td>$rowItemData['Vendor']</td>";
echo "<td>$rowItemData['Date']</td>";
echo "<td>$rowItemData['Total']</td>";
echo "</tr>";
}
You should specify the indexes of the array $rowitemdata.
For example:
echo"<tr><td>".$rowitemdata['Vendor']."
I haven't gone through your full code, but I can see wrong syntax for while
while($rowItemData = sqlsrv_fetch_array($resultItemData)){
echo "<tr>";
echo "<td>".$resultItemData['Seller']."</td>";
echo "<td>".$resultItemData['Vendor']."</td>";
echo "<td>".$resultItemData['Date']."</td>";
echo "<td>".$resultItemData['Total']."</td>";
echo "</tr>";
}
or
while($rowItemData = sqlsrv_fetch_array($resultItemData)) :
echo "<tr>";
echo "<td>".$resultItemData['Seller']."</td>";
echo "<td>".$resultItemData['Vendor']."</td>";
echo "<td>".$resultItemData['Date']."</td>";
echo "<td>".$resultItemData['Total']."</td>";
echo "</tr>";
endwhile;
Update:
still you can optimize the code, I just gave sample working
Let's assume your query actually produces a result, because you don't check that it does:
$resultItemData = sqlsrv_query($con, $queryOrders);
$header = <<<HEREDOC
<table border="1" align="center">
<tr>
<th>Seller</th>
<th>Vendor</th>
<th>Date</th>
<th>Total</th>
</tr>
HEREDOC;
echo $header;
while($rowItemData = sqlsrv_fetch_array($resultItemData)) {
echo "<tr>
<td>{$rowItemData['Seller']}</td>
<td>{$rowItemData['Vendor']}</td>
<td>{$rowItemData['Date']}</td>
<td>{$rowItemData['Total']}</td>
</tr>";
}
echo '</table>';
To actually check that the query works, you might want to do this instead. This is just to debug/illustrate error checking for the query execution. You wouldn't want to output an error to the screen, but rather log it. You probably want to just output the table header/footer and skip the while/loop entirely.
$resultItemData = sqlsrv_query($con, $queryOrders);
if (resultItemData === false) {
die(print_r(sqlsrv_errors(), true));
}

PHP - How can I print out my database table?

I have a php code to print out my table including its column name. The printing has to be dynamic because it has to print different size/length tables based on a user input. :
<table>
<?php
while ($row = mysqli_fetch_array($results)) {
while ($fieldInfo = mysqli_fetch_field($results)) { ?>
<th> <?php echo $fieldInfo->name; ?> </th>
<td> <?php echo $row[$fieldInfo->name] ?> </td>
<?php }
} ?>
</table>
this is the query for $results:
$tName = $_POST["tableNames"]; //this data is recieved from another page
require_once("conn.php");
$sql = "SELECT * FROM $tName";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
my code correctly prints out the table name as well as the first row data but it is not formatted correctly here is how it looks:
additionally. for some reason it only prints out the first row even though im using a while loop.
My advice to you is to prepare two arrays:
First one: containing column names and second: containing data.
When use two foreach to generate first row with header and second one to display data. You have forgot to add <tr> tags to divide rows.
Use
The mysqli_fetch_field() function returns the next column in the result set as an object. It will only returns all column names not the records of table.
You need to use mysqli_fetch_array() for getting all records:
while ($info = mysqli_fetch_array($results,MYSQLI_ASSOC)) {
{
echo $info['rid'];
echo $info['level'];
....
}
I ended up with using a taras' suggestion of storing the column names in an array:
<table>
<?php
while ($fieldInfo = mysqli_fetch_field($results)) { ?>
<th> <?php echo $fieldInfo->name; ?> </th>
<?php
$colNames[] = $fieldInfo->name;
?>
<?php }
while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<?php for ($i=0; $i<sizeof($colNames); $i++) { ?>
<td><?php echo $row[$colNames[$i]] ?>
<?php } ?>
</tr>
<?php } ?>
</table>
As of my understand, do you want to display all table and their columns?
So you can format like below
$sql = "SHOW TABLES FROM dbname";
$result_tables = mysqli_query($link, $sql);
echo "<table border=1>";
echo "<tr><td>Table name</td><td>Fields name</td></tr>";
while($row = mysqli_fetch_array($result_tables)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
$sql2 = "SHOW COLUMNS FROM ".$row[0];\\row[0] is used to get table name
$result_fields = mysqli_query($link, $sql2);
echo "<td>";
while($row2 = mysqli_fetch_array($result_fields)) {
echo $row2['Field'].',';
}
echo "</td>";
echo "</tr>";
}

How to pass options value from each table row?

I am creating a table with rows which has options in each cells. The options are received from database table. Since each row has a options cell, I have to receive the value from each row. In select tag, the 'name' is incremented with the rows. But I am only getting the value of the last row.
Attaching the code section here.
for ($i = 1; $i <= $_GET['pno']; $i++) {
echo'<tr>';
echo "<td>$i</td>";
echo '<td><select name="prod_$i">'; echo "prod_$i";
//Query for production table gets processed.
$qry_pr="SELECT * FROM production";
$result_pr=mysql_query($qry_pr);
$rows_pr=mysql_affected_rows($con);
//Production options get filled from the table data.
for($j=0;$j<=$rows_pr;$j++)
{
$res_arr_pr=mysql_fetch_array($result_pr);
echo "<option value=$res_arr_pr[0]>$res_arr_pr[1]</option>";
//$res++;
}
//mysql_close($con);
echo '</select></td>';
echo '<td><select name="prod_mu_$i">';
//Query for measurement_unit table gets processed.
$qry_mu="SELECT * FROM measurement_unit";
$result_mu=mysql_query($qry_mu);
$rows_mu=mysql_affected_rows($con);
//Unit options get filled from the table data
for($k=0;$k<=$rows_mu;$k++)
{
$res_arr_mu=mysql_fetch_array($result_mu);
echo "<option value=$res_arr_mu[0]>$res_arr_mu[1]</option>";
}
echo '</td>';
echo '</tr>'; echo "prod_$i";
}
echo'</table><br>';
Hope I am clear with the query.
Thank you.
You have placed the SQL Query inside the for loop making it heavy. Because it will perform the same query over and over again. If you tweak the code a little you can use perform a single query and use that for all loop iterations.
<?php
//initialize blank
$productions = $measurements = '';
// create the production select box
$qry_pr="SELECT * FROM production";
$result_pr=mysql_query($qry_pr);
if( mysql_num_rows($result_pr) )
{
$productions .= "<select name='prod_%index%'>";
while( $rec_pr = mysql_fetch_row($result_pr) )
{
$productions .= "<option value='{$rec_pr[0]}'>{$rec_pr[1]}</option>";
}
$productions .= "</select>";
}
// create the measurement select box
$qry_mu="SELECT * FROM measurement_unit";
$result_mu=mysql_query($qry_mu);
if( mysql_num_rows($result_mu) )
{
$measurements .= "<select name='prod_mu_%index%'>";
while( $rec_mu = mysql_fetch_array($result_mu) )
{
$measurements .= "<option value='{$rec_mu[0]}'>{$rec_mu[1]}</option>";
}
$measurements .= "</select>";
}
?>
<table>
<?php for($i=1;$i<=$_GET['pno'];$i++): ?>
<tr>
<td><?php echo str_replace('%index%',$i,$productions); ?></td>
<td><?php echo str_replace('%index%',$i,$measurements); ?></td>
</tr>
<?php endfor; ?>
</table>
Change:
echo '<td><select name="prod_$i">'; echo "prod_$i";
to:
echo '<td><select name="prod_' . $i . '[]">'; echo "prod_$i";
mysql_affected_rows will only give you the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query. Your performing a SELECT, so the $rows_mu value will be wrong.
Instead of:
$rows_mu=mysql_affected_rows($con);
//Unit options get filled from the table data
for($k=0;$k<=$rows_mu;$k++)
{
$res_arr_mu=mysql_fetch_array($result_mu);
echo "<option value=$res_arr_mu[0]>$res_arr_mu[1]</option>";
}
try this:
//Unit options get filled from the table data
while ($res_arr_mu = mysql_fetch_array($result_mu))
{
echo "<option value=$res_arr_mu[0]>$res_arr_mu[1]</option>";
}

SQL Image Database assembling rows into HTML cells and rows

I have a database of images which I want to output as a gallery ...
I want to display each image in its own cell <td>image1</td> and limit the number of cells to 7 per row.
<tr>
<td>image1</td><td>image2</td><td>image3</td><td>image4</td><td>image5</td><td>image6</td><td>image7</td>
</tr>
Then a new row would be created and continue to output all the images.
<tr>
<td>image8</td>
and so on ..
I know how to do a query, but I am lost as to how to assemble the rows into the format I am looking for.
Can anyone please help me it would be greatly appreciated. Thanks.
First run your query, then get the mysql_fetch_assoc in a variable. Then echo your beginning tags for the table and tr. Then create a foreach loop of the query assoc, as another variable such as row, and echo $row['image'] in a td. This will add a new td with the image for every entry in the database. Then echo your closing tags for the tr and table.
$query = mysql_query("SELECT image FROM table_name");
$query_a = mysql_fetch_assoc($query);
echo "<table><tr>"
foreach ($query_a as $row)) {
echo "
<td>" . $row['image'] . "</td>
";
}
echo "</tr></table>";
Not tested, but try something like this
<table>
<?php
// make sure there is at least 1 row first
$cnt = 0;
$while($row = mysql_fetch_assoc($query))
{
if(++$cnt == 1) {
echo '<tr>';
} elseif($cnt % 7 == 0) {
echo '</tr><tr>';
}
// show images in <td>'s
echo "<td>" . $row['image']. "</td>";
}
echo '</tr>';
?>
</table>
Keep it simple:
Query the database to get the desired information, loop through the results, construct a new row come each new loop.
$sql = "Select * from table";
mysql_query($sql) or die(mysql_error());
if(mysql_num_rows !=0)
{
// Found at least one record, create table
echo "<table>";
echo "<tr>";
while($row = mysql_fetch_assoc($sql)
{
$cell_count = 0;
// Create a new row for each record found
echo "<td>" . $row['image_column']. "</td>";
$cell_count++;
if($cell_count == 7)
{
echo "</tr>";
echo "<tr>";
$cell_count = 0;
}
}
// Close the table
echo "</tr>";
echo "</table>";
}

PHP function creates tables, how to add database ID as URL parameter?

I have some code that creates a table like this:
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td" . $i;
echo "></td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
$counter = 0;
foreach($row as $cell)
{
if($counter == 0)
{//1st column
echo "<td><strong>" .$cell. "</strong></td>";
}
elseif($counter == 8)
{//7th column
echo "<td><img src=\"http://php.alton.com/image.php/image.jpg?width=100&height=100&cropratio=1:1&image=".$cell."\" /></td>";
}
elseif($counter == 9)
{//eighth column
echo "<td><strong>" .$cell. "</strong></td>";
}
else
echo "<td>$cell</td>";
//inside your default td
$counter++;
}
echo "</tr>\n";
}
I am trying to get the MySQL result from column 0 (ID) and pass this variable into a URL parameter in the result. I want the SQL results in Column 8 to create a link that includes the ID from column 0. For example: "/details.php?ID=43" where the ID comes from the 1st column in the row. Does this make sense?
Your output code is inherently bad since it relies on the order the results are returned in from the database. This may work now, but is an incredibly fragile way of doing things. You should refer to your fields (columns) by name, not by the order they're returned in. You're also needlessly complicating your output code with that inner loop and if…else construct. Try something along these lines:
<?php while ($row = mysql_fetch_assoc($result)) : ?>
<tr>
(substitute 'col1' etc by the actual columns names)
<td><strong><?php echo $row['col1']; ?></strong></td>
<td><?php echo $row['col2']; ?></td>
…
<td>
<img src="http://php.alton.com/image.php/image.jpg?width=100&height=100&cropratio=1:1&image=<?php echo $row['image']; ?>" />
</td>
…
</tr>
<?php endwhile; ?>
I'm not quite sure about your actual question, but approaching your problem like this may answer it already.

Categories