Select 1 row and display it in a table with 2 columns - php

How can I make a select in database and display that row in a table with 2 columns.
Here is my select
$query="select Interval from Interval_Orar";
$result=mysqli_query($dbc,$query) or die("query failed: " . mysqli_error($dbc));
echo '<table>';
while ($row=mysqli_fetch_array($result))
{
echo'
<tr>
<td>'.$row['Interval'].'</td>
</tr>';
}
echo '</table>';
what i what to display is a table like this
<tr>
<td>Interval 1</td>
<td>Interval 2</td>
</tr>
<tr>
<td>Interval 3</td>
<td>Interval 4</td>
</tr>
<tr>
<td>Interval 5</td>
<td>Interval 6</td>
</tr>
what i dont know to make is to put that 2 by 2 select in the while

You could just do another mysqli_fetch_array in the loop, check if there was a result
and display either an empty cell or one with the content.
Then at the end of the loop you only need to check if the second mysqli_fetch_array had a result. (The empty cell is optional, it depends if you require it e.g. for styling, add not value or other things)
while ($row=mysqli_fetch_array($result))
{
echo'<tr>';
echo '<td>'.$row['Interval'].'</td>';
$row=mysqli_fetch_array($result);
if( $row ) {
echo '<td>'.$row['Interval'].'</td>';
} else {
echo '<td></td>';
}
echo '</tr>';
if( !$row ) {
break;
}
}
Another way would be to use a $counter and a $counter%2 to check in which column the result should be displayed and if an <tr> or </tr> needs to be added, but that would require more work.
EDIT
This is not tested as I neither have php not a mysql setup server right here, but making a function out of it would allow you to re use it with any column count:
function createRows( $result, $columns ) {
if( $columns <= 0 ) {
return;
}
$row = true; //initialize it with true so that the first mysqli_fetch_array will be called
while($row !== null ) {
echo'<tr>';
for( $i=0 ; $i<columns ; $i++ ) {
if( $row !== null && $row=mysqli_fetch_array($result) ) {
echo '<td>'.$row['Interval'].'</td>';
} else {
echo '<td></td>';
}
}
echo '</tr>';
}
}

Dump your entire result set into an array so you can manually move the pointer.
The inside your loop it would be (in plain English)
column1 = row1
column2 = row1+1
row = row + 1
repeat.

Related

Trying to get MySQL results to display horizontally

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;
} );

Add column of checkboxes in final row of table read in from postgresql db

I have a table that is read in from a postgresql database. I am having trouble adding checkboxes to a final row in the table so that I can then, using an add to basket function pass items to a basket.php file.
Firstly I need to add a checkbox to a final column on each row so that I can check against the items I want to add when I click add to cart. I am struggling massively with this. Any help would be greatly appreciated as my code is below. If you could explain what needs to be done that'd be awesome as I can learn from it.
<table border="1">
<tr>
<th>ref</th>
<th>title</th>
<th>platform</th>
<th>description</th>
<th>price</th>
<th>select</th>
</tr>
<?php $resource = pg_query ($connect, "select refnumber,title,platform,description,price from csgames");
while ($a = pg_fetch_array ($resource)) {
echo "<tr>";
for ($j = 0; $j < pg_num_fields ($resource); $j++) {
echo "<td>".$a[$j] ."</td>";
}
echo "</tr>";
}
?>
</table>
Try this
while ($a = pg_fetch_array ($resource)) {
echo "<tr>";
for ($j = 0; $j < pg_num_fields ($resource); $j++) {
echo "<td>".$a[$j] ."</td>";
}
echo '<input type="checkbox" name="items[]" value="'.$id.'" />'; //replace with item id
echo "</tr>";
}
Submitting the form will populate the items[] variable
$items = $_POST['items']; //array of itemid selected
output
---------
var_dump(items) = Array ( [items] => Array ( [0] => item123 [1] => item125 ) )

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>";
}

displaying values from database into an html table

i want to display values from a database (a list of categories) into a table that has 2 columns and x number of rows.
I want my web page to display like this:
Apes Cats
Apples Cherries
Bats Tigers
Berries Zebras
Instead of
Apes Apples
Bats Bears
Cats Cherries
Tigers Zebras
Here is my code so far:
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
while ($category = mysqli_fetch_array($data)) {
?>
<tr>
<td><?php echo $category['cat_name'] ?></td>
</tr>
<?php } ?>
</table>
Here's the basic idea:
You get the count of the data via num_rows
Divide by two.
Now, the result of your division will be the number of rows.
Output a loop echoing value for row x and x+ num rows. For example the output of line 1 would be :
<tr><td>$row[val1][data]</td><td>$row[val5][data]</td></tr>
So, your loop would ultimately output:
val 1 | val 5
val 2 | val 6
val 3 | val 7
val 4 | val 8
The loop should end when your incrementing variable = num_rows. Should be pretty straightforward from there. Good luck.
Try this (haven't tested it though):
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
# Calculate total rows and half rows, rounded up
$full_row_count = mysqli_num_rows($data);
$half_row_count = ceil($full_row_count / 2);
$i = 0;
while ($i <= $half_row_count) {
# Set the result pointer for first column ...
mysqli_data_seek($data, $i);
$category_1 = mysqli_fetch_array($data);
# ... then calculate the offset for the second column ...
$col_2_offset = $i + $half_row_count;
# .. and make sure it's not larger than total rows - 1
if ($col_2_offset <= $full_row_count - 1) {
mysqli_data_seek($data, $col_2_offset);
$category_2 = mysqli_fetch_array($data);
} else {
$category_2 = array('cat_name' => '');
}
?>
<tr>
<td><?php echo $category_1['cat_name'] ?></td>
<td><?php echo $category_2['cat_name'] ?></td>
</tr>
<?php
$i++;
}
?>
</table>
Hope this helps !
You can add an another variable say, $i, to the loop and just increment this through as follows:
<table border="0" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="400" cellpadding="3" cellspacing="3">
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$i=1;
while ($category = $data->fetch_row()) {
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $category[1] ?></td>
</tr>
<?php
$i++;
} ?>
</table>
EDIT: Updated to fetch row data for each result and assume that cat_name is the second item in the array i.e. $category[1].
If it doesn't have to be a table and your fine with browsers that support CSS 3, then you can use CSS columns:
http://jsfiddle.net/QKuDL/
Otherwise you'll need to sort the results first (untested - PHP is not my strong suit):
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$col_count = 2;
$max_items_per_col = ceil( mysqli_num_rows ( $data ) / $col_count );
$cols = array(array());
$col = 0;
while ($category = mysqli_fetch_array($data)) {
if (count($cols[$col]) >= $max_items_per_col) {
$col++;
}
$cols[$col][] = $category['cat_name'];
}
?>
<table> <!-- all of those attributes should be CSS instead -->
<?php for ($i = 0; $i < $max_items_per_col; $i++) { ?>
<tr>
<?php foreach ($cols as $col) { ?>
<td><?php if(isset($col[$i])) echo $col[$i]; ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
<?php
$query = "SELECT * FROM category ORDER BY cat_name";
$data = mysqli_query($dbc, $query);
$midpoint = ceil($data->num_rows / 2);
$i=0;
while ($category = $data->fetch_array()) {
if ($i < $midpoint)
$left[$i] = "<td>" . $category['cat_name'] . "</td>";
else
$right[$i - $midpoint] = "<td>" . $category['cat_name'] . "</td>";
$i++;
}
print "<table>";
for ($j=0; $j < $i; $j++)
{
print "<tr>" . $left[$j];
if (array_key_exists($j, $right)) print $right[$j];
print "</tr>";
}
print "</table>";

PHP/MySQL Output Data in TD's

How would I go about imposing a restriction on the number of HTML table columns when querying the database.
For example, I have a MySQL table with the following values:
myTable:
id color
1 red
2 blue
3 green
4 pink
5 purple
And when I run my query, instead of showing all rows in traditional table rows, e.g.
<table>
<?php
while {
echo "<tr><td>$row['color']</td></tr>;
}
?>
</table>
Instead, I would like to impose something where, every three td's, a new tr is created.
For example, it would output something like this:
<table>
<tr>
<td>red</td>
<td>blue</td>
<td>green</td>
</tr> <-- Notice how after 3 columns, a new table row is created.
<tr>
<td>pink</td>
<td>purple</td>
</tr>
</table>
Any way to achieve this?
In order to achieve this, you can use a combination of a counter and a modulus (%) operator:
<table>
<?php
$count = 0;
while($row = mysql_fetch_array($results)) {
$outputTr = ($count % 3) == 0;
if($outputTr) echo '<tr>';
echo '<td>' . $row['color'] . '</td>';
if($outputTr) echo '</tr>';
$count++;
}
?>
</table>
To achive this, put in a simple counter that resets every 3 table datas.
<?php
echo "<table><tr>";
$count = 0;
foreach($data as $key => $color)
{
if($count == 3)
{
$count = 0;
echo "</tr><tr>";
}
$count++;
echo "<td>".$color."</td>";
}
echo "</tr></table>";
?>

Categories