I am currently working on a Table class in php. This class creates tables dynamic by only giving values for the column names and an array from the selected data. I am stuck on displaying the values in the correct way I want to. This is how it's looking right now:current table . I thought it could be my the array. In the array all the values are the other way around like this: array . The 2nd is before the 1st id. Here is my Table Class:
public function displayTable($columns, $values = 0)
{
$this->setTable("<table class='table table-striped table-hover'>
<thead class='thead-inverse'>
<tr>");
foreach ($columns as $columnName) {
$this->setTable($this->getTable(). "<th>".$columnName."</th>" );
}
$this->setTable($this->getTable(). "</tr></thead><tbody>");
for ($x = 0; $x != sizeof($values); $x++) {
$this->setTable($this->getTable(). "<tr>");
foreach ($values as $value) {
$this->setTable($this->getTable(). "<td>".$value[$x] ."</td>");
var_dump($value);
}
$this->setTable($this->getTable(). "</tr>");
}
$this->setTable($this->getTable(). "</tbody></table>");
var_dump($this->getTable());
}
I tried applying a order by on my select query. That will get rid of my problem on the array. Displaying the items right in the td is the issue. The td is created constantly until it got no values and starts a new array just like I showed with the picture. So is there anyway to fix the problem of displaying these values under the table header td?
By looking to your array image,it seems you use fetchAll() to get records from the db.
fetchAll() provide numeric+associative array in combination. That's why your record coming like this:-
array(
'userId'=>2,
0=>2,
'userEmail'=>'some value',
1=>'same mail id'
);
Now you have only two theads # and email, but the second foreach provide you 4 <td> after each iteration, and hense table distorted.
Solution:- You have to use fetchAll(PDO::FETCH_NUM) to resolve your issue and after that change your code like below:-
public function displayTable($columns, $values = 0){
$this->setTable("<table class='table table-striped table-hover'><thead class='thead-inverse'><tr>");
foreach ($columns as $columnName) {
$this->setTable($this->getTable(). "<th>".$columnName."</th>" );
}
$this->setTable($this->getTable(). "</tr></thead><tbody>");
for ($x = 0; $x != sizeof($values); $x++) {
$this->setTable($this->getTable(). "<tr>");
foreach ($values as $key=> $value) {
$this->setTable($this->getTable(). "<td>".$value[$key] ."</td>");
}
$this->setTable($this->getTable(). "</tr>");
}
$this->setTable($this->getTable(). "</tbody></table>");
var_dump($this->getTable());
}
Related
I have this:
$keys = Keys_Info::all();
foreach ($keys as $key)
{
$rank = 1; //Example.. In real it's variable..
DB::table('keys_info')
->where('id', $key->id)
->update(['rank' => $rank]);
}
This only updates first row, not all. How get this to update all rows?
EDIT
foreach($keys as $key)
{
print $key->id; //Example printing all keys
foreach($results as $results)
{
print $key->id; //Example printing all keys
if (in_array($key->example, $array))
{
print $key->id; //Example printing first row key!
$rank = 1; //Example
DB::table('keywords_info')
->where('id', $key->id)
->update(['url_rank' => $rank]);
}
}
}
I didn't explain well at first, this is whole code I use. I figured out that it does not work in IF statement
As you are updating all rows you can simply do like below
DB::table('keys_info')->update(['rank' => $rank]);
If you still want to pass the id you can do like below
//Fetch all ids in array
$keys=Keys_Info::pluck('id') OR Keys_Info::value('id')
//apply in query
DB::table('keys_info')->whereIn('id', $keys)->update(['rank' => $rank]);
I have spent a lot of time trying to find ways to do the following, and have researched as much as I can but am still stuck.
I have a table 'pool_a' that at the minute has 2 columns - team_id and team_name.
I need to echo the id and the name into a nested foreach loop.
Now I can do this if I am just worried about the name, but now my query includes the ID too, I can't work out how to get both bits of data for each row in my table.
Here's how I get it to work with team_name...
for ($i=0;$i<$num;$i++) {
$team=mysql_result($result,$i,'team_name');
$team_names[$i] = $team;
echo $team . "<br>";
}
foreach ($team_names as $team) {
foreach ($team_names as $opposition) {
if ($team != $opposition) {
echo "<tr><td>" . $team . "<td><input type=\"text\"<td>versus<td><input type=\"text\">" . $opposition . "</tr>";
}
}
}
This is great, and outputs the correct fixture list and with input boxes for scores, but I need to add a hidden data input with team_id as the value. For example:
Here is what I have so far. Note that I have been learning about PDO's and new 5.5 techniques, so you will notice my style of code will be different in the next snippet.
require_once "pdo_enl_connect.php";
$database=dbNB_connect();
$query=$database->query ("SELECT team_id, team_name from pool_a");
while ($row = $query->fetch(PDO::FETCH_NUM)) {
printf ("%s %s<br>", $row[0], $row[1]);
$teams=array($row[0], $row[1]);
}
foreach ($teams as $key=>$value) {
echo "$key and $value<br>";
}
$database=NULL;
The output I get for the foreach loop is
0 and 5
1 and Silhouettes //silhouettes being the last team in the table.
ANy help would be much appreciated, and please let me know if I can edit my question to make it clearer in any way.
Thanks
Your while loop should look like this:
$teams = array();
while ($row = $query->fetch(PDO::FETCH_NUM)) {
// $row and array($row[0], $row[1]) are the same here
$teams[] = $row;
}
You need to initialize $team = array(); before your loop.
Then add your tuple to the teams array by doing either array_push($teams, array($row[0], $row[1])); or $teams []= array($row[0], $row[1]);`
This question already has answers here:
MySQL query to get column names?
(22 answers)
Closed 9 years ago.
I am attempting to retrieve the column headers for html headers from a MySQL query. The structure of my application is such that the column headers aren't static (sometimes there are 4, sometimes 7, etc.) For some unbearable reason I can't find a simple way to get the column names from any given query.
My end goal is to output an html table from the query.
Well if you get the query as an associative array, you can do something like this:
$query = "Select [stuff]";
$results = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_assoc($results)) {
if ($i < 1) {
foreach($row as $key => $val) {
echo $key;//column name
}
}
//Do other stuff
$i++;
}
And yes, I know they should be doing mysqli_..., but this is my example using old mysql_...
Edit
To expand on this:
$query = "Select [stuff]";
$results = mysql_query($query);
$i = 0;
echo "<table>";
while ($row = mysql_fetch_assoc($results)) {
echo "<tr>";
if ($i < 1) {
foreach($row as $key => $val) {
echo "<td>".$key."</td>";//column name
}
}
echo "</tr>";
echo "<tr>";
foreach($row as $key => $val) {
echo "<td>".$val."</td>";//column name
}
echo "</tr>";
//Do other stuff
$i++;
}
You can use function mysql_list_fields for getting column names.
Code below gets data from sql. Including header column
// Data, depends on your sql statement
$sql_dt = array(); // make sure it is array
foreach( $sql_dt as $key => $val ) {
$data[] = <<< EOH
<tr>
<th>$val['column_name']</th> <tr/>
<th>$val['column_age']</th>
<tr/>
EOH;
}
$table_dt = implode( $data );
echo <<< EOT
<table>
<tr>
<th>Name</th> <tr/>
<th>Age</th>
<tr/>
{$table_dt}
<table/>
EOT;
I am trying to make pull key => value pairs out of an array by using a do { ....} while {there are values left inside the array.
I am using a function to query mysql for and then to insert all the values inside an array
function table_array($query) {
$table_array = array();
$data_fetched = false;
while ($array = mysql_fetch_assoc($query)) {
if (!$data_fetched) {
foreach ($array as $key => $value) {
$table_array[$key] = $value;
//$data_fetched = true;
}
}
}
return $table_array;
}
and then i am using another loop to extract the data from the array
function get_table($table_array) {
$header_written = false;
echo "<table border=1>";
if ($table_array) {
do {
echo "<tr>";
foreach ($table_array as $columns => $values) {
echo "<td> {$values} </td>";
}
echo "</tr>";
}while ($table_array);
}
echo "</table>";
}
However this causing my loop to run infinitely , why can't i use it just as though i would be doing while mysql_fetch_assoc is true.
I tried using a flag but that will stop it running after only one record is being extracted.
What you really need here are two foreach loops. The outer iterates over rows, and the inner iterates over columns:
echo "<table>";
// Iterates over rows
foreach ($table_array as $row) {
echo "<tr>";
// Iterates over columns (table cells)
foreach ($row as $col=>$value) {
echo "<td>{$value}</td>";
}
echo "</tr>";
}
echo "</table>";
Though your fetching process works, it can be simplified and improved. You don't need a foreach to assign columns to your $table_array. You can simply append the whole fetched row using the [] syntax. Not sure what the purpose of $data_fetched was, so I removed that as well
while ($array = mysql_fetch_assoc($query)) {
// Use the [] syntax to append the whole row onto $table_array
// No need to add each column of the fetched row separately
$table_array[] = $array;
}
Finally, the reason it didn't work the way you setup your do-while is that iterating over a regular array is not similar to fetching from a MySQL result set. The fetch calls will eventually return FALSE when no rows remain. Unless you are actively removing elements from an array while iterating over it, and eventually deleting the empty array, it will always evaluate to a boolean TRUE.
You need to use either foreach($array as $key => $value){ ... } or do{ ... } while ($array).
You should not use both, as you only have one set of data to loop over. I would stick with foreach as it is safer, and can do exactly what you need.
If you feel you need to use a do/while, then you need to pop a value off the $table_array each time you are inside the loop. This way, the $table_array will become empty at some point. Currently, in your code, the $table_array is always full so the while loop continues endlessly.
I have a MySQL database with 35 different columns labeled 1-35. The data is displayed in a dynamic table. I am looking for the PHP code that would allow me to apply a CSS class to specific cells based on what is returned inside them.
EXAMPLE: Column 1 can return either TRUE or FALSE value. If a TRUE value is returned, I want to give that cell a different background color, or highlight it.
I have the CSS class as:
.highlight {
background-color: #FC0;
}
After the CSS class has then been applied to the specific cells from columns 1-35, I would like the PHP code that can total the number of highlighted cells in the column labeled TOTAL.
Can't seem to find the PHP code to tie all this together. If someone could advise, I'd be very grateful.
<td class="<?php if ($row['item'] == TRUE)
{
echo 'highlight';
$highlights++;
}
else
{
echo 'no_highlight';
}
?>"><?php echo $row['item'];?></td>
and then...
<td id="totalHighlights"><?php echo $highlights;?></td>
EDIT: Sample code...
<?php
//We've queried the database and passed the results into $result via mysql_fetch_assoc().
while ($row = $result)
{
//Clear highlights and values arrays for each row.
$highlights = array();
$values = array();
foreach($row as $entry)
{
if ($entry == TRUE)
{
//Put a truthy value into highlights array.
array_push($highlights, 1);
}
else
{
//Put a falsey value into highlights array.
array_push($highlights, 0);
}
//Push actual field value to values array.
array_push($values, $entry);
}
echo '<tr class="row">';
//Create cell with total highlights per row using the array_sum() of highlights.
echo '<td class="row_total_highlights">'.array_sum($highlights).'</td>';
//Create each value cell and populate them with each field value from values array.
$i = 0;
foreach ($values as $value)
{
echo '<td class="entry ';
echo ($highlights[$i] == 1 ? 'trueClass' : 'falseClass');
echo '">'.$value.'</td>';
$i++;
}
echo '</tr>';
}