I have a mySQL table which can be simplified down to something like this:
animal breed
Cat Persian
Cat Siamese
Dog Alsatian
Dog Poodle
I want to display the information in this form:
<table>
<tr>
<td class="heading">Cat</td>
</tr>
<tr>
<td class="body">Persian</td>
<td class="body">Siamese</td>
</tr>
<tr>
<td class="heading">Dog</td>
</tr>
<tr>
<td class="body">Alsatian</td>
<td class="body">Poodle</td>
</tr>
</table>
So far, I have a query like this:
$query = "SELECT * FROM aa_animal";
$result = mysql_query($query, $MySQL_extranet) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$resultarray[] = $row;
}
Then I think I am going to need a pair of nested foreach() loops, but it is the handling of the multi-dimensional array that gets me hopelessly lost.
foreach("unique_animal") {
<tr>
<td class-"heading">$animal</td>
</tr>
if ($animal=="unique_animal") {
foreach("row") {
<tr>
<td class-"body">$breed</td>
</tr>
}
}
How do I manipulate $resultarray to get the right values for $animal, $breed, etc?
PROGRESS SO FAR
Justin's reply provided the solution to the problem as described above. However the real-life page has a lot more columns in the database table. Here is the code for a halfway file between the simple example I gave originally and the page I am trying to create.
<?php
$countryid='spain';
// MySQL query to select hotels and display all the hotel info
$query = "SELECT hid, hotel, pricefrom, place, region, country, picture, property, prop2, rooms, summary, lat, lng, zoomloc, breakfast, searchparam, specialoffer, biz_model, ta_rating, bc_rating FROM ex_hotel WHERE country LIKE '%$countryid%' AND showhide = 'show' ORDER BY orderr DESC";
$result = mysql_query($query, $MySQL_extranet) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
if (isset($resultarray[$row['region']])) {
$resultarray[$row['region']][] = $row['hotel'];
}else{
$resultarray[$row['region']] = array($row['hotel']);
}
}
ksort($resultarray);
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<table width="500" border="1" cellspacing=" 4" cellpadding="4">
<?php foreach($resultarray as $region => $hotel)
{
echo '<tr><td colspan="2" style="background-color:#ddd">'.$region.'</td></tr>';
foreach($hotel as $value) {
echo '<tr><td width="250px">'.$value.'</td>';
}
foreach($hid as $value2) {
echo '<td>'.$value2.'</td></tr>';
}
}?>
</table>
</body>
</html>
All those values in the mySQL query need to be used in the table, but how do I get them?
You should group data when fetching
while($row = mysql_fetch_assoc($result))
{
if (isset($resultarray[$row['animal']]))
$resultarray[$row['animal']][] = $row['breed'];
else
$resultarray[$row['animal']] = array($row['breed']);
}
And then, display it
foreach($resultarray as $animal => $breed)
{
echo '<tr><td class="heading">'.$animal.'</td></tr>';
foreach($breed as $value)
echo '<tr><td class="body">'.$value.'</td></tr>';
}
EDIT:
If you need more columns, what you have to do is storing full row instead of one item:
while($row = mysql_fetch_assoc($result))
{
if (isset($resultarray[$row['region']]))
$resultarray[$row['region']][] = $row;
else
$resultarray[$row['region']] = array($row);
}
And then, you can also fetch those rows
foreach($resultarray as $region => $rows)
{
echo '<tr><td class="heading">'.$region.'</td></tr>';
// this way (display everything)
foreach($rows as $row)
foreach($row as $key => $value)
echo '<tr><td class="body">'.$key.': '.$value.'</td></tr>';
// or this way (if you want to display only specific item)
foreach($rows as $row)
echo '<tr><td class="body">Hotel: '.$row["hotel"].' / price: '.$row["pricefrom"].'</td></tr>';
}
Related
How to make so a checkbox is added beside each row in a dynamic table? So if i get 5 result from databse i want to display 5 checkbox next to these results.
<table border="2">
<tr>
<th>title</th>
</tr>
<?php
include 'database.php';
$valid_query = "SELECT * FROM agencies ";
$valid_result = mysqli_query($link, $valid_query);
while ($row = mysqli_fetch_array($valid_result)) {
echo '<tr>';
echo '<td>'.$row['title'].'</td>';
<input type = 'checkbox' name = '$row[title]'>
echo '<tr>';
}
?>
</table>
I'm trying to make a search form that return some data from an oracle database,it works fine except that it skip the first row of table .
I used the following code :
enter code here
if(isset($_POST['search']) && !empty($_POST["search_box"])){
$name=$_POST['search_box'];
$sql='SELECT deejays.name,available_dates.data, available_dates.venue,available_dates.location FROM deejays,available_dates';
$sql .=" WHERE deejays.name ='{$name}'";
$sql .=' AND pk_id=fk_id';
$verify="SELECT deejays.name FROM deejays WHERE deejays.name ='{$name}'";
$stid = oci_parse($conn,$sql );
oci_execute($stid);
if (oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)){
echo "<table width=\"100%\" align=\"center\" cellpadding=\"5\" cellspacing=\"5\">
<tr class=\"source\">
<td colspan=3 align=\"center\"><h1>The facebook tour dates for ".$name." are:</h1></td>
</tr>
<tr align=\"center\" class=\"source1\">
<td><strong>DATA</strong></td>
<td><strong>VENUE</strong></td>
<td><strong>LOCATION</strong></td>
</tr>";?>
<?php while($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)){ ?>
<tr align="center" class="rows">
<td ><?php echo $row['DATA'];?></td>
<td ><?php echo $row['VENUE'];?></td>
<td ><?php echo $row['LOCATION'];?></td>
</tr>
<?php } ?>
</table>
<?php } else {
$stid = oci_parse($conn,$verify );
oci_execute($stid);
if (oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{ echo "This artist hasn't records on facebook/bandsintown<br>
enter code here
the expected result is:
and the real result is:
The second image shows that the first row is skipped,how could I solve this?Thanks in advance
As I commented, oci_fetch_array() will return an array containing the next result-set row of a query. Which means everytime you call it, the cursor will move to the next row. I have two suggestions.
First
Load all the result into an array after oci_execute(). And count the array if it has any row.
oci_execute($stid);
$result = array();
while($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS))
{
$array[] = $row;
}
//check if result is not empty
if (count($result)) {
//the table part here.
}
And when you want to display it in html table, use foreach loop to iterate the array and build the <tr>.
<?php foreach($result as $row) { ?>
<tr align="center" class="rows">
<t ><?php echo $row['DATA'];?></td>
<td><?php echo $row['VENUE'];?></td>
<td><?php echo $row['LOCATION'];?></td>
</tr>
<?php } ?>
SECOND
You can use oci_fetch_all() to load all the rows from the query into an array.
oci_execute($stid);
//$result will have all the result of the current query
$count = oci_fetch_all($stid, $result);
if ($count) {
//table part here
}
And building the <tr> will be the same as the first.
Another way is to use buffered query. But this will depend on many factors.
I have a table of users and a table of scores in golf tournaments for those users. When a user plays a tournament he records a score in the results table using a form. I want to display a table of results showing the full list of users and the scores in the tournaments. There are eight columns of scores in the table - one for each course played. I am struggling with the php code to display the resulting scores. Where a player has played, his score appears correctly but if the following player in the table has not played his score is shown as the score for the player above him in the table. This continues down the list until a genuine score is encountered. I have tried to find the answer to this without success. Here is my code for just a single course. If I can overcome the problem for this I am sure the code will work for the other courses.
$query = "SELECT * FROM emg_users ORDER BY user_login";
$results=mysql_query($query);
$results_array = array();
while ($row = mysql_fetch_array($results)) {
$results_array[$row['ID']] = $row;
}
foreach ($results_array as $id => $record) {
$player = $record['user_login'];
?>
<tr>
<td class="padded_c" nowrap="nowrap"><?php echo $player;?></td> <!-- Player name -->
<?php
$query = "SELECT * FROM 0_tournament_test WHERE player = '".$player."' AND course = 'St_Andrews'";
$results=mysql_query($query);
$results_array = array();
while ($row = mysql_fetch_array($results)) {
$results_array[$row['id']] = $row;
}
foreach ($results_array as $id => $record) {
$pplayer = $record['player'];
if ($pplayer = $player) {
$sta = $record['score'];
}
else {
unset($sta);
}
$id++;
}
?>
<td class="padded_c" nowrap="nowrap"></td>
<td nowrap="nowrap"><?php echo $sta;?></td>
<td nowrap="nowrap"><?php echo $rsg;?></td>
<td nowrap="nowrap"><?php echo $bet;?></td>
<td nowrap="nowrap"><?php echo $oak;?></td>
<td nowrap="nowrap"><?php echo $kia;?></td>
<td nowrap="nowrap"><?php echo $cng;?></td>
<td nowrap="nowrap"><?php echo $mer;?></td>
<td nowrap="nowrap"><?php echo $oly;?></td>
<td nowrap="nowrap"><?php echo $allshots;?></td>
<td nowrap="nowrap"><?php echo $sss;?></td>
<td nowrap="nowrap"><?php echo '';?></td>
</tr>
<?php
$id++;
}
?>
</table>
I think you forgot some login...
Little Change in your code :--
if ($pplayer == $player) {
$sta = $record['score'];
}
else
{
unset($sta);
}
Add this condition to your code...
Here the value of $table will be passed from another file and it will be a table name in a database.
With that table name ($table) am trying to fetch its column names and all the values in the table and make the table look like an actual one we see in phpMyAdmin.
As a result of the code below. I can only get the column names. But not the data. Please tell me what should i do to perform the task of showing the datas in the table
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="display" rel="datatable">
<thead>
<tr>
<?php
//echo"select * from $table";
$qq=mysql_query("show columns from $table");
if(mysql_num_rows($qq)>0){
//$i=1;
echo '<tr>';
while($rs = mysql_fetch_row($qq))
{
$sel=mysql_query("select * from $table");
$fetch=mysql_fetch_object($sel);
//while($fetch=mysql_fetch_object($sel))
//{
?>
<td><?php echo $fetch->$rs[0];?></td>
<?php
//}
//$i++;
}
echo '</tr>';
}
else
{
?>
<tr>
<td colspan="11">No data to display</td>
</tr>
<?php
}
?>
</tbody>
</table>
Yes only columns will be printing because you are printing $rs[0];?> where $rs holds object for mysql_query qq and it holds your column query only not
"select * from $table"
this.
Why dont you try displaying columns as a single row in html table and then try displaying data from other php set with seperate query structure .
Hope this way it helps.
I coudn't fix your code because it was getting ugly, so i remade it:
php:
function mysql_fetch_all($res) {
$result = array();
while ($row = mysql_fetch_row($res)) {
$result[] = $row;
}
return $result;
}
function getColumnsAndData($table) {
$table = mysql_real_escape_string($table);
$q1 = mysql_query("show columns from $table");
$q2 = mysql_query("select * from $table");
return array(mysql_fetch_all($q1), mysql_fetch_all($q2));
}
list($columns, $data) = getColumnsAndData($table);
?>
html
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="display" rel="datatable">
<thead>
<tr>
<?php foreach ($columns as $column): ?>
<td><?php echo $column[0] . ' ' . $column[1] ?></td>
<?php endforeach; ?>
<tr>
</thead>
<tbody>
<?php if (count($data) > 0): ?>
<?php foreach ($data as $row): ?>
<tr>
<?php foreach ($row as $value): ?>
<td><?php echo $value ?></td>
<?php endforeach; ?>
<tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td>No data to display</td>
</tr>
<?php endif; ?>
</tbody>
</table>
Im writing a function to get the parent and child ids but for the third loop there is a
problem the loop gets even the previous loops id also .
How can i avoid it?
<?
$results = '
<table>
<thead>
<tr >
<td id="ticket" align="center" ><b>Task<br />ID</b></td>
<td id="ticket" align="center" ><b>col1</td>
<td id="ticket" align="center" ><b>col2</td>
</tr>
</thead>
<tbody>';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$results .='
<tr >
<td align="center">
'.$row['Task_id'].'
</td>';
$results .= '<td align="center">';
$gg = mysqli_query($dbc,"select * from Tasks where ParentTask_Id='".$row['Task_id']."'");
echo "<br>";
while ($rowdd = mysqli_fetch_assoc($gg))
{
$results .= $rowdd['Task_id']."<br><br>";
$gg2 = mysqli_query($dbc,"select * from Tasks where ParentTask_Id='".$rowdd['Task_id']."'");
while ($rowdd2 = mysqli_fetch_assoc($gg2))
{
$results2 = $rowdd2['Task_id']."<br><br>";
}
echo "<br>";
}
// $results .= $car ;
// $results .= $t;
$results .='</td>';
$results .=' <td align="left" >'?>
<?
$results .= $results2;
$results .='</td>';
$results .='
</tr>';
}
?>
Is the $results variable empty? I only see it being concatenated.
Also, on your table you have multiple ids that are the same. You either need to change that to a class or have a unique value for each id.