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

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.

Related

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.

Retrieve column names from MySQL query [duplicate]

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;

how to add data to array using for loop in php?

I am making a mysql query . I want to add result to an array. suppose I am selecting all user from user table. I want to get everyones name. if the row=5 i want to save every name according to the row index.
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
//echo ($row);
$num=mysql_num_rows($query);
echo ($num);
for ($i=1; $i<=$num;$i++){
//here I want to save all name to an array.
}
Please help.
You might be looking for something like this:
$rows = array();
// while there are more records, add them to `$rows`
while($row = mysql_fetch_assoc($result)) {
$rows []= $row;
}
Note that mysql_fetch_assoc() will just return false if there are no (more) records in the result set. So you don't need the call to mysql_num_rows()
$num = mysql_num_rows($query);
if($num > 0)
{
while($row = mysql_fetch_array($query)
{
$names[] = $row['name'];
}
}
That will create an array called $names which you can loop through later. Also, it's a good time to look into mysqli_* functions, or PDO.

rewind one step back in mysql_fetch_array()

this is the values in the $result
id name
1 a
2 b
2 c
2 d
3 e
..
I'm creating a loop function using mysql_fetch_array()
while($row = mysql_fetch_array($result)) {
$temp_id = $row['id'];
while($temp_id == $row['id']) {
if($temp_id == $row['id']) {
mysql_fetch_array($result);
}
$temp_id = $row['id'];
echo $row['name'].",";
}
echo "<br/>";
}
this works but the problem is, the mysql_fetch_array jumps on one of the values during the transition of the id's..
I want the values of this to be like these
a
b,c,d
e
my question is, is there a simple rewind function that will step only once in the rows?
I have searched about the mysql_data_seek() but I think this would require additional control variables like $i to locate the address..
thanks.. any suggestions and function samples will be very great!
Use one loop with mysql_fetch_array first to create an array of the rows. Then, iterate over the rows themselves.
Based on the update to your question it seems like you would want to use GROUP_CONCAT in the query, but you can still do it in PHP:
$rows = array();
while($row = mysql_fetch_assoc($result)) {
if (!isset($rows[$row['id']]) {
$rows[$row['id'] = array();
}
$rows[$row['id']][] = $row['name'];
}
foreach ($rows as $row) {
echo implode(',', $row) . "<br>";
}
Try this code
while($row = mysql_fetch_array($result)) {
$temp[$row['id']][] = $row['name'];
}
foreach($temp as $row) {
echo implode(',', $row) . '<br/>';
}

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