Need help changing table array by moving a column in PHP - php

I have been handed the task of making some changes to a PHP webpage that was coded by someone who has left the company and my Php is exactly exeprt.
The page in question displays a database table in a SQL server that allows you to update values via an update page.
Currently the Update function sits under the 'Action' column at the end of the table and I need to relocate the 'Action' column to the start of the table before the 'Name' column.
When I try to make changes, I break the table array and the 'Update' function no longer works.
Current order of columns are;
Name,
Value,
Details,
Action
The new order of columns attempting to achieve
Action,
Name,
Value,
Details
I have also included the code in question.
Any assistance would be appreciated
Note** It is a Php website running on a Windows box and connecting to a MSSQL Server 2008
$query = sqlsrv_query($conn, 'SELECT * FROM Database_Values ORDER BY Name ASC');
// Did the query fail?
if (!$query) {
die( FormatErrors( sqlsrv_errors() ) );
}
// Dump all field names in result
$field_name = "";
foreach (sqlsrv_field_metadata($query) as $fieldMetadata) {
foreach ($fieldMetadata as $name => $value) {
if ($name == "Name") {
$field_name .= $value . '-';
}
}
}
$field_name = substr_replace($field_name, "", -1);
$names = explode("-", $field_name);
?>
<div style="max-height:610px; overflow:auto;">
<table border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" class="table" width="100%">
<tr>
<?php
foreach ($names as $name) {
?>
<th><?php echo $name; ?></th>
<?php
}
?>
<th>Action</th>
</tr>
<?php
// Fetch the row
while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
//print_r($row);
?>
<tr>
<?php
foreach ($row as $key => $eachrow) {
?>
<td nowrap="nowrap">
<?php echo $eachrow; ?>
</td>
<?php
}
?>
<td nowrap="nowrap">
<?php $groupid = $_SESSION["gid"] ;
if($groupid!='1') {
?>
<a href="javascript:void(0);" title="Permission Restricted" >Update</a>
<?php } else { ?>
Update
<?php } ?>
</td>
</tr>
<?php
}
?>
</table>
</div>

All you need to do is change the order of the th and td cells in the html
$query = sqlsrv_query($conn, 'SELECT * FROM Database_Values ORDER BY Name ASC');
// Did the query fail?
if (!$query) {
die( FormatErrors( sqlsrv_errors() ) );
}
// Dump all field names in result
$field_name = "";
foreach (sqlsrv_field_metadata($query) as $fieldMetadata) {
foreach ($fieldMetadata as $name => $value) {
if ($name == "Name") {
$field_name .= $value . '-';
}
}
}
$field_name = substr_replace($field_name, "", -1);
$names = explode("-", $field_name);
?>
<div style="max-height:610px; overflow:auto;">
<table border="1" cellspacing="0" cellpadding="0" bordercolor="#ccc" class="table" width="100%">
<tr>
<th>Action</th>
<?php
foreach ($names as $name) {
?>
<th><?php echo $name; ?></th>
<?php
}
?>
</tr>
<?php
// Fetch the row
while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
//print_r($row);
?>
<tr>
<td nowrap="nowrap">
<?php $groupid = $_SESSION["gid"] ;
if($groupid!='1') {
?>
<a href="javascript:void(0);" title="Permission Restricted" >Update</a>
<?php } else { ?>
Update
<?php } ?>
</td>
<?php
foreach ($row as $key => $eachrow) {
?>
<td nowrap="nowrap">
<?php echo $eachrow; ?>
</td>
<?php
}
?>
</tr>
<?php
}
?>
</table>
</div>

Related

Codeigniter multiple foreach loop

I have two tables meals type and meals. I want to print each meals corresponding to its meals type.
Error is that only showing last meals type meals only
view page is like
View
<?php
foreach ($mealstype as $type) {
?>
<h2><?php echo $type->type; ?></h2>
<table class="table table-bordered">
<tr>
<th>Meals</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
foreach ($meals as $meals_get) {
?>
<tr>
<td><?php echo $meals_get->item; ?></td>
<td><?php echo $meals_get->price; ?></td>
</tr>
<?php } ?>
<tr>
<td> <input type="checkbox" class="ck" value="total"> Toal</td>
<td>2050</td>
</tr>
</tbody>
</table>
<?php
}
?>
Controller
function availability() {
$this->data['mealstype'] = $this->Home_model->mealstype();
foreach ($this->data['mealstype'] as $type) {
$typeid = $type->id;
$meals[] = $this->Home_model->meals($typeid, $hotel_id);
}
$this->data['meals'] = $meals[];
$this->load->view('home2', $this->data);
}
Please check this answer
Controller:
public function availability() {
$build_array = array();
mealstype= $this->Home_model->mealstype();
foreach($mealstype as $row){
$build_array[] = array(
'parent_array' => $row,
'child_array' =>$this->Home_model->meals($row->id,$hotel_id),
'child_sum' =>$this->Home_model->meals_sum($row->id,$hotel_id)
);
}
$this->data['build_array'] = $build_array;
}
and the view page is like this:
View:
<?php foreach($build_array as $type){?>
<h2><?php echo $type['parent_array']->type;?></h2>
<table class="table table-bordered">
<tr>
<th>Meals</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
foreach ($type["child_array"] as $meals_get) {?>
<tr>
<td><?php echo $meals_get->item;?></td>
<td><?php echo $meals_get->price;?></td>
</tr>
<?php }?>
<tr>
<td> Toal</td>
<td>2050</td>
</tr>
<?php } ?>
Controller, check "hotel_id"
function availability()
{
$this->data['mealstype'] = $this->Home_model->mealstype();
if( count( $this->data['mealstype'] ) > 0 )
{
foreach($this->data['mealstype'] as $type)
{
$type->meals = $this->Home_model->meals( $type->id, $hotel_id ); // hotel_id no declared???
}
}
$this->load->view('home2', $this->data);
}
View
<?php if( count( $mealstype ) > 0): foreach( $mealstype as $type ): ?>
<h2><?php echo $type->type; ?></h2>
<table class="table table-bordered">
<thead>
<tr>
<th>Meals</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php if( count( $type->meals ) > 0 ): foreach( $type->meals as $meals_get ): ?>
<tr>
<td><?php echo $meals_get->item; ?></td>
<td><?php echo $meals_get->price; ?></td>
</tr>
<?php endforeach; endif; ?>
<tr>
<td><input type="checkbox" class="ck" value="total"> Toal</td>
<td>2050</td>
</tr>
</tbody>
</table>
<?php endforeach; endif ?>
Try to replace into this :
function availability() {
$data = array();
$data['mealstype'] = $this->Home_model->mealstype();
foreach ($data['mealstype'] as $type) {
$typeid = $type->id;
$type->meals = $this->Home_model->meals($typeid,$hotel_id);
}
$this->load->view('home2', $data);
}
check it and print_r($data); what it comes set on the basis of that in view file..
You have $hotel_id I am not sure where you set this I can not see it any where else.
We also need to see your model
public function availability() {
$data['mealstypes'] = array();
$mealstypes = $this->home_model->mealstype();
foreach ($mealstypes as $mealstype)
{
$meals = array();
$meals_results = $this->home_model->meals($mealstype->id, $hotel_id);
foreach ($meals_results $meal_result) {
$meals[] = array(
'mealstype' => $meal_result->mealstype,
'price' => $meal_result->price
);
}
$data['mealstypes'][] = array(
'type' => $mealstype->type
'meals' => $meals
);
}
$this->load->view('someview', $data);
}
View
<?php foreach ($mealstypes as $mealstype) {?>
<h2><?php echo $mealstype['type'];?></h2>
<?php foreach ($mealstype['meals'] as $meal) {?>
<?php echo $meal['mealstype'];?>
<?php echo $meal['price'];?>
<?php }?>
<?php }?>

Mysql display rows as columns [duplicate]

This question already has an answer here:
MySql Transpose Row into Column and Column into Row [duplicate]
(1 answer)
Closed 7 years ago.
I want to display rows as columns.
This is mysql table called Term
|Name ||Year ||HTML ||CSS ||Js ||
|Year1 ||2013-08-30||90 ||70 ||70 ||
|Year2 ||2014-08-30||100 ||65 ||80 ||
|Year3 ||2015-08-30||80 ||95 ||90 ||
What I want is to display as columns like this
|Subject||Year1 ||Year2 ||Year3 ||
|HTML ||90| ||100 ||80 ||
|CSS ||70| ||65 ||95 ||
|JS ||70| ||80 ||90 ||
Code
<tr>
<th>Code</th><th>Subject</th><th>year1</th>
<th>year2</th><th>year3</th>
</tr>
<?php
$query = mysql_query("SELECT * FROM term WHERE Stdid='$id'");
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $key => $value) {
?>
<tr>
<th><?php echo $key ?></th>
<th><?php echo $value?></th>
<th>99</th><th>00</th>
</tr>
<?php } } } ?>
</table>
My result only works for the first year
|Subject||Year1 ||Year2 ||Year3||
|HTML ||90| ||? ||? ||
|CSS ||70| ||? ||? ||
|JS ||70| ||? ||? ||
You first need to transpose all data in a temporary array before you can output it again. I'll give you 2 methods to do this.
Method 1: just fetch every row and switch the row index by the column index:
<table>
<tr>
<th>Subject</th>
<th>year1</th>
<th>year2</th>
<th>year3</th>
</tr>
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'database');
$id = 1;
$report = array();
$columnIndex = 0;
$query = $mysqli->query("SELECT HTML, CSS, Js FROM term WHERE Stdid='$id'");
while ($results = $query->fetch_assoc()) {
foreach ($results as $course => $score) {
$report[$course][$columnIndex] = $score;
}
$columnIndex++;
}
foreach ($report as $course => $results) { ?>
<tr>
<th><?php echo $course; ?></th>
<?php foreach ($results as $score) { ?>
<th><?php echo $score; ?></th>
<?php } ?>
</tr>
<?php } ?>
</table>
Method 2: Fetch all rows in an array, so it becomes an array of arrays and use array_map with callback NULL to transpose it (See example 4 at http://php.net/manual/en/function.array-map.php).
You need to add the course names in the initial array to include them in the end result.
<table>
<tr>
<th>Subject</th>
<th>year1</th>
<th>year2</th>
<th>year3</th>
</tr>
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'database');
$id = 1;
$data = array(array('HTML', 'CSS', 'Js'));
$query = $mysqli->query("SELECT HTML, CSS, Js FROM term WHERE Stdid='$id'");
while ($row = $query->fetch_assoc())
{
$data[] = $row;
}
$data = call_user_func_array('array_map', array_merge(array(NULL), $data));
?>
<?php
foreach ($data as $row): ?>
<tr>
<?php foreach ($row as $value): ?>
<th><?php echo $value?></th>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
Try this.
<table width = "1093" align="center" bgcolor="pink">
<tr align="center">
<td colspan="6"><h2>View Term</h2></td>
</tr>
<tr align="center" bgcolor="">
<th>S.N</th>
<th>Subject</th>
<th>Year 1</th>
<th>Year 2</th>
<th>Year 3</th>
</tr>
<?php
$db = mysqli_connect("localhost","root","YOURPASSWORD","YOURDATABASE");
if (mysqli_connect_errno())
{
echo"The Connection was not established" . mysqli_connect_error();
exit();
}
$get_term = "SELECT * FROM term WHERE Stdid='$id'";
$run_term = mysqli_query($db,$get_term);
$i =0 ;
while ($row=mysqli_fetch_array($run_term ))
{
// Get data from database.
// Change the input in $row[''] if the name of column is different in your tble "term".
$subject=$row['subject'];
$year1=$row['year1'];
$year2=$row['year2'];
$year3=$row['year3'];
$i++;
?>
<tr align="center">
<td> <?php echo $i;?></td>
<td><?php echo $subject;?></td>
<td><?php echo $year1;?></td>
<td><?php echo $year2;?></td>
<td><?php echo $year3;?></td>
</tr>
<?php }?>
</table>

PHP MYSQL Associate array and table

Here is a code.
This loads all the header part (i.e the header for the table) dynamically from the database.
The below code works fine. But the column is mismatched.
i.e. the first row first column of the header is blank and there is a dislocation in the table.
Code
<table border="1">
<?php
$book_query = mysql_query("select * from book_master");
$i = 0;
while($row = mysql_fetch_assoc($book_query))
{
$columns = array_keys($row);
?>
<th>
<?php
foreach($columns as $column)
{
?>
<td><?php echo $column; ?> </td>
</th>
<?php
}
?>
<tr>
<?php
foreach($row as $key=>$value)
{
?>
<td><?php echo $value; ?></td>
<?php
}
?>
</tr>
<?php
$i++;
}
?>
</table>
EDIT:
Here is my print_r($columns) value:
Array ( [0] => Author Name [1] => Book Name [2] => Rating [3] => Location )
I know the problem is with the loop. Could someone help me out?
You can try to change
<th>
<?php
foreach($columns as $column)
{ ?>
<td><?php echo $column; ?> </td>
<?php
}
?>
</th>
to
<tr>
<?php
foreach($columns as $column)
{ ?>
<th><?php echo $column; ?> </th>
<?php
}
?>
</tr>
Just remove TH tag because its create one extra cell, so your layout messed up
<table border="1">
<?php
$book_query = mysql_query("select * from book_master");
$i = 0;
while($row = mysql_fetch_assoc($book_query))
{
if($i == 0){
$columns = array_keys($row);
?>
<?php
foreach($columns as $column){ ?>
<td><?php echo $column; ?> </td>
<?php } ?>
<?php } ?>
<tr>
<?php
foreach($row as $key=>$value){ ?>
<td><?php echo $value; ?></td>
<?php } ?>
</tr>
<?php
$i++;
}
?>
</table>
Hope this will help someone.
Just I have replaced the TH tag with TR and the output is perfect.
<table border="1">
<?php
$book_query = mysql_query("select * from book_master");
while($row = mysql_fetch_assoc($book_query))
{
$columns = array_keys($row);
?>
<tr>
<?php
foreach($columns as $column){ ?>
<td><?php echo $column; ?> </td>
<?php } ?>
</tr>
<tr>
<?php
foreach($row as $key=>$value){ ?>
<td><?php echo $value; ?></td>
<?php } ?>
</tr>
</table>

Got stuck with populating mysql table in html table [duplicate]

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>

Using foreach to display results

I'm trying to write some sort of forum homepage, based off work someone else did. Here's what I've got so far:
Forums
<?php
$crumbs = explode(",", $user['data']['depts']);
foreach ($crumbs as &$value) {
$data = $db->query("SELECT * FROM tbl_depts WHERE id = '" . $value . "'");
$crumb = $data->fetch_assoc();
$data = $db->query("SELECT * FROM tbl_forums WHERE deptid = '" . $value . "'");
$forumcount = $data->num_rows;
$forum = $data->fetch_assoc();
?>
<div class="h3top"><?php echo $crumb['name']; ?></div>
<div class="info2alt">
<?php
while (($row = $data->fetch_array()) !== FALSE) {
$forum[] = $row;
}
foreach ($forum as $row) {
if ($forumcount >= 1) {
if ($forum['lastpost'] == "") {
$forum['lastpost'] = "--";
}
?>
<div class="info4">
<table width="100%" border="0" cellspacing="1" cellpadding="4">
<tr>
<td width="55%" align="left" valign="middle" class="zebraodd"><?php echo $row['name']; ?></td>
<td width="10%">Threads: <?php echo $forum['threadcount']; ?><br />Posts: <?php echo $forum['postcount']; ?></td>
<td width="35%">Last Post: <?php echo $forum['lastpost']; ?></td>
</tr>
</table>
</div>
<?php
}
?>
<?php if ($forumcount >= 1) { ?>
<div class="info3bottom"></div>
<?php
}
}
?>
</div>
<?php
}
?>
This is the current data in the table:
Now, when I try to use this code, I get this:, such that the first one is shown so many times, however, the next one does not appear.
How do I fix this?
you want to use $value['threadcount'] etc. $forum is the array containing all the rows. i wonder that you get some output at all …
fetch_assoc() will only fetch a single row from the resultset. you'd have to use a loop to fill an array:
while(($row = $data->fetch_assoc()) !== FALSE) {
$forum[] = $row;
}
you can then iterate over your $forum array with a foreach loop:
foreach($forum as $row) {
echo htmlspecialchars($row['threadcount']);
// etc.
}
trying to fix this mess …
<?php
$crumbs = explode(",", $user['data']['depts']);
foreach ($crumbs as $crumb) { ?>
<div class="h3top"><?php echo htmlspecialchars($crumb['name']);?></div>
<?
}
$result = $db->query("SELECT * FROM tbl_forums WHERE deptid = " . (int)$id . "");
$forumcount = $result->num_rows;
while(($row = $data->fetch_assoc()) !== FALSE) {
if ($row['lastpost'] == "") { $row['lastpost'] = "--";}
?>
<div class="info2alt">
<div class="info4">
<table width="100%" border="0" cellspacing="1" cellpadding="4">
<tr>
<td width="55%" align="left" valign="middle" class="zebraodd"><?php echo htmlspecialchars($forum['name']); ?></td>
<td width="10%">Threads: <?php echo htmlspecialchars($forum['threadcount']); ?><br />Posts: <?php echo htmlspecialchars($forum['postcount']); ?></td>
<td width="35%">Last Post: <?php echo htmlspecialchars($forum['lastpost']); ?></td>
</tr>
</table>
</div>
<div class="info3bottom"></div>
<?php
}
?>

Categories