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.
Related
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));
}
I use a MySql query to select data from my DB and then print it in the form of a HTML Table. It works perfectly, fine but sometimes the table consists of hundreds of rows and the webpage looks incredibly akward. Is there a way to split the table side by side into 2 or 3 halves.
Present Output
Desired output
PHP
<?php
....
echo "<h3>Classes attended :</h3>";
echo "<table class='dates' border='1'>";
foreach ($results as $dates) {
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
What would be the best way to achieve it?
Help would be appreciated.
You can use PHP to determine in your loop if the loop index is divisible by a certain number using something like this:
echo "<h3>Classes attended :</h3>";
echo "<table class='dates' border='1'>";
$rowCount = 1;
$numRows = count($results);
$maxRows = 12;
foreach ($results as $dates) {
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
if($rowCount % $maxRows == 0 && $rowCount != $numRows) {
echo "</table><table class='dates' border='1'>";
}
$rowCount ++;
}
echo "</table>";
That's the basics of doing this. Basically in your loop you're testing each index to see if it's divisible by $maxRows, and if so then you're going to close your table and open a new one. You'll have to add the styling to place the tables side by side.
If you wanted to expand upon this concept you can set $maxRows to be an evaluation of $numRows. For instance if you wanted to split the items as close as possible to half in order to show just two tables, you could do... $numRows = count($results); $maxRows = round($numRows / 2);
Inspired by Robert Wade's answer:
<?php
....
echo "<h3>Classes attended :</h3>";
$i=0;
$maxRows=10;
foreach ($results as $dates) {
$a=$i/$maxRows == 0 ? "<table class='dates' border='1'>":"";
$b=$i/$maxRows == 0 ? "</table>":"";
echo $a;
echo "<tr><td width='50%'>";
echo $dates->db_date;
echo "</td>";
echo "<td width='50%'>";
echo $dates->day_name;
echo "</td>";
echo "</tr>";
echo $b;
$i++;
}
?>
At last, add some css style to the tables.
You can also use array_chunk() for splitting your results. Or instead of displaing a lot of tables next to each other you can make pagination and get only some range in your query. For example:
SELECT * FROM `clients` LIMIT 5, 10
Selects 10 rows beggining from row 5. Now, when you change your page, just change limit values.
Here is the problem:
I need to know if there is a way to do an upward rowspan on a <th> element on a form.
I am reading some rows inside a DB that I need to put inside an html table.
I am doing something like:
echo "<table>";
while($result = $resultSet->fetch())
{
echo "<tr>";
echo "<td>$result['Name']</td>";
echo "<td>$result['Job']</td>";
echo "</tr>";
}
ehco "</table>";
First steps are easy until I needed to 'span' together two adjacent cells that contains the same value.
For exemple if someone have the same name but had two jobs I would like them to have something like :
echo "<tr>";
echo "<td rowspan='2'>$result['Name']</td>";
echo "<td>$result['Job']</td>";
echo "</tr>";
But I can't predict how many jobs someone have (except they all have at least one and that they are all in order).
exemple of record in MySQL table
Name/**/Jobs
Paul/**/Jobs1
Simon/**/Jobs23
Simon/**/Jobs45
Roger/**/Jobs67
(All simon's jobs are 'behind one another', they are grouped. If Paul had a second job it would be the second record in the table 'pushing' simons jobs down).
So I need to change the rowspan value of the first element to fit how many jobs that person have.
This is why I would need to know if it is possible to do a upward span because i could just display every on of them and count how many jobs each person have and do a rowspan that would merge the table cell upward.
It would certainly be easier then fetching every row in the DB then looping throught them all and checking how many jobs a person have to 'span' the cells now and then display them all and then skipping them. and so on.
Thanks
A situation like this calls for pre-processing. Like so:
$people = array();
while($result = $resultSet->fetch())
{
if( !isset($people[$result['Name']])) $people[$result['Name']] = array();
$people[$result['Name']][] = $result['Job'];
}
echo "<table>";
foreach($people as $name=>$jobs)
{
echo "<tr>";
echo "<td rowspan=\"".count($jobs)."\">".$name."</td>";
echo "<td>".array_shift($jobs)."</td>";
echo "</tr>";
foreach( $jobs as $otherjob)
{
echo "<tr><td>".$otherjob."</td></tr>";
}
}
echo "</table>";
Done!
What you're looking for doesn't exist in HTML. But you can do it like this:
$currName = $result['Name'];
echo "<tr>";
if($currName==$prevName)
{
echo "<td> </td>";
}
else
{
echo "<td>$result['Name']</td>";
}
echo "<td>$result['Job']</td>";
echo "</tr>";
$prevName = $currName;
Rather than using rowspan, just nest a table in the second column with all of the jobs for that person.
echo "<tr>";
echo "<td>$result['Name']</td>";
echo "<td>";
echo "<table>"
foreach($jobs as $job): //$jobs holds the job values for the current name
echo "<tr><td>";
echo $job;
echo "</td></tr>";
endforeach;
echo "</table>";
echo "</td>";
echo "</tr>";
Note: you will need to preprocess the result set to get a 2D array for this method (see answer from Niet the Dark Absol).
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>";
}
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>";
}