How to loop through arrays in PHP to display the results - php

I have a query which retrives two colums of multiple rows from the db.I want it to display this in a table using php,I have to use two dimensional arrays i guess.Please help on how shall i proceed.
while($row=mysql_fetchrow_array($qry))
{
Please guide how to store the columns in the array[][]
}
[Please guide on how to display the result in the display page]
foreach( )
{
}

// store the columns in the array[][]:
$res = array();
while($row=mysql_fetch_array($qry, MYSQL_NUM)) {
$res[] = $row;
}
// display the result in the display page
echo "<table>\n";
foreach($res as $row) {
echo "<tr>\n";
foreach ($row as $fld) {
echo "<td>$fld</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

Related

Get SQLite Table Data into HTML Table

I have an SQLite database and using PHP to serve up and interact the data with.
I am trying to build an HTML table with for each SQLite table columns as the HTML Table Columns and then for each row in the SQLite table render as a for each row in the HTML table.
Issue is that each sql row data is only rendered into one html table row (with current code) (should be for each row) question would be how I go about getting the sql row data into array for looping through to render html table rows.
Currently I have;
PHP get the SQL Columns into the HTML table & SQl Row data(foreach) into HTML Table Rows (foreach)
//get table count
$countTable = $dbConnect->querySingle("SELECT COUNT(*) as count FROM ".$table['name']."");
if($countTable){
//data exists, do work
//new query to get table data
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
//init arrays
$dataColumns = array();
$dataRows = array();
while($row = $query->fetchArray(SQLITE3_ASSOC))
{
//add columns to array, checking if value exists
foreach($row as $key => $value)
{
if(in_array(''.$key.'', $dataColumns)){
//column already in array, dont add again.
}else{
//column not in array, add it.
$dataColumns[]=array(
'column'=>$key
);
}
//while in this foreach do I add the row values to an array or do it again outside this loop?
//below does not work, only adds to the one array item and renders one HTML Table row with multiple SQL Table row values
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
}
}
//build HTML table
echo '<div class="table-responsive"><table class="table"><thead><tr>';
//build columns from array... works
foreach($dataColumns as $dataColumn){
echo '<th>'.$dataColumn['column'].'</th>';
}
//close table column headers 7 start HTML table body...
echo '</tr></thead><tbody>';
//Issue is here, how do I get the each row (value is either null or not null) to
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['row_item'].'</td>';
}
echo '</tr>';
//close table body & table...
echo '</tbody></table></div>';
}else{
//table has no data
echo 'no data in the selected table';
}
I rewrote this to do it all in one loop like this.
$firstRow = true;
echo '<div class="table-responsive"><table class="table">';
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
if ($firstRow) {
echo '<thead><tr>';
foreach ($row as $key => $value) {
echo '<th>'.$key.'</th>';
}
echo '</tr></thead>';
echo '<tbody>';
$firstRow = false;
}
echo '<tr>';
foreach ($row as $value) {
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table></div>';
You might find it clearer to read? It also avoids building an array of all the dataRows in memory.
Try to replace
$dataRows[]=array(
'row_item'=>$row[''.$row.'']
);
with
$dataRows[]=$row;
Put this line at first line inside your while loop (or general outside the foreach loop over your columns), because adding a row is not connected analyzing your columns.
Then, in your output foreach, you should find the rows with all columns selected from your database query inside $dataRow (here symbolized with column1, column2, …):
echo '<tr>';
foreach($dataRows as $dataRow){
echo '<td>'.$dataRow['column1'].'</td>';
echo '<td>'.$dataRow['column2'].'</td>';
echo '<td>'.$dataRow['column3'].'</td>';
echo '<td>'.$dataRow['column4'].'</td>';
echo '<td>'.$dataRow['column5'].'</td>';
echo '<td>'.$dataRow['column6'].'</td>';
echo '<td>'.$dataRow['column7'].'</td>';
// etc.
}
echo '</tr>';
After all your code should look like this (a bit simplified):
$query = $dbConnect->query("SELECT * FROM ".$table['name']." ORDER BY id DESC");
$dataColumns = array();
$dataRows = array();
while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
$dataRows[] = $row;
foreach ($row as $key => $value) {
//Bilding $dataColumns, see Question
}
}
echo '<div class="table-responsive"><table class="table"><thead><tr>';
foreach ($dataColumns as $dataColumn) {
echo '<th>'.$dataColumn['column'].'</th>';
}
echo '</tr></thead><tbody>';
echo '<tr>';
foreach ($dataRows as $dataRow) {
foreach ($dataRow as $columnName => $columnValue) {
echo '<td>'.$columnValue.'</td>';
}
}
echo '</tr>';
echo '</tbody></table></div>';
Thanks to akrys
in the while loop, but outside the foreach column loop;
//$dataRows = array();
$dataRows[]=$row;
and in the building of the HTML Table;
foreach($dataRows as $dataRow){
echo '<tr>';
foreach($dataRow as $key => $value){echo '<td>'.$value.'</td>';}
echo '</tr>';
}

Storing db value into php array and then looping through the array

What would the benefits be of storing db values into an array and then looping through the array vs just using a while loop?
Outputting db results to an array:
$records = array();
if($results = $db->query("SELECT name, address FROM town")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results->free();
}
}
Loop through array:
foreach($records as $r) {
$r->name;
}
VS a simple While loop:
if($result = $db->query("SELECT name, address FROM town")) {
if($count = $result->num_rows) {
while($row = $result->fetch_object()) {
echo $row->name, ' ', $row->address, '<br />';
}
$result->free();
}
}
Just a while loop and printing the result is easy and fast, but in certain times you want to do more then just print the array and then it becomes handy if you already work with arrays.
The most common use for this is freeing the resultset, allowing you to perform other db queries (updates, inserts...) before actually making any use of the results you got in the first place.

PHP to display all MySQL columns without knowing how many there are

I need some PHP code to display all columns (without referencing how many there are, or their names) in a comma separated, one row per line, format.
I am a novice and have only ever worked with examples where I reference the columns by name:
$result = mysql_query("select * from table1");
while($row = mysql_fetch_array($result))
{
echo $row["field1"].','.$row["field2"];
}
In the above code, can I create a looping echo command based on the number of columns (how do I get this value?) to print all the columns – if I can display the column names in the first row of output, great, but it’s not essential. Or, is there a specific command that will achieve the same result?
I think the answer is a foreach($row as....) - but not sure where to go from there.
Yep you can do a foreach but if you just want to display your values in a CSV style you can do :
$firstRow = true;
while($row = mysql_fetch_array($result))
{
if ($firstRow) {
$firstRow = false;
$columns = array_keys($row);
// prints all the column names
echo implode(',', $columns);
}
// print all the values
echo implode(',', $row);
}
If you want more control over what you output you can use a foreach :
while($row = mysql_fetch_array($result))
{
foreach ($row as $column => $value) {
echo $column.' : '.$value."\n";
}
}
You'll want to count the $row array
while($row = mysql_fetch_array($result))
{
$columns = count($row);
for($i = 0; $i < $columns; $i++)
{
echo $row[$i].',';
}
}
Or you can use foreach() as #Dagon has pointed out -
while($row = mysql_fetch_array($result))
{
foreach($row as $column)
{
echo $column . ',';
{
}
Please, stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO.

Obtaining data from query in multidimensional array

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]);`

Looping through Array in PHP returned from MySQL Query

I have a part of an application that loops through a return of a MySQL query (as we all know) in the form of an Array. However, I need several different format settings placed on some of the items returned, for example, one column needs Japanese currency, the other has American currency and one of the returned items is a link to an image.
I would use the names of the column, however this same function that I am using to accomplish this will be used for many different tables.
This is what I have for the loop so far.
while($row = mysql_fetch_array($result)) {
for($i=0;$i<=count($row);$i++) {
if($row[i]==$row['Yen_Price']) {// I didn't expect this to work...but this is what I would like to do.
echo "Hello";
}
echo "<td>" . $row[$i] . "</td>";
}
}
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $value) {
if ($key == 'Yen_Price') {
echo "Hello";
}
echo "<td>$value</td>";
}
}
Having said that, using the same function to process all results from all possible tables will soon be rather unmanageable. You should customized this to fit the occasion like so:
while ($row = mysql_fetch_assoc($result)) {
echo "<td>Foo: $row[foo]</td>";
echo "<td>Bar: $row[bar]</td>";
}
I'd markup these results specific to each table but if you want it to be ultimately flexible, try this smelly code
// using mysql_fetch_assoc() as we don't need the numeric indices
while($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
echo '<td>';
switch ($col) {
case 'US_Price' :
printf('$%0.2f USD', $val);
break;
case 'Yen_Price' :
printf('¥%0.2f', $val);
break;
case 'image' :
printf('<img src="%s">', htmlspecialchars($val));
break;
}
echo '</td>';
}
}
Note that this is a known antipattern and you should really think about another way to approach the problem.
Use the below code. You can modify it as you want.
$select=" WRITE YOUR SELECT QUERY HERE ";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
// YOU CAN USE HERE FOR EACH LOOP AS PER YOUR REQUIREMENTS.
Thanks
Before I became a framework fanatic I used to have a bit different approach. My db library had set of methods that returned me array of record sets. This way I keep my db interaction totally separate from how I consume the record sets. Having done this, its easy to set up a grid template which can look at array and then act accordingly. Here is some pseudo code
$recordSets = $db->returnRecordSets("select some, columns from tablename");//extra param if I need array to be associative
$recordSetsCount = count($recordSets);
if($recordSetsCount == 0){ echo 'Nothing to be done!'; //exit or return or break here}
for($i=0; $i< $recordSetsCount; $i++ == 0){
$recordSet = $recordSets[$i];
/*Inspect the $recordSet array and use it*/
}

Categories