/    Sign up×
Community /Pin to ProfileBookmark

Is there a command to output all fields from a MYSQL selection?

I may have worded that a bit wrong. Basically I have a report generator that needs to run various reports using an SQL query on a MySQL database and then output the results. With most of the pages I have built in the past using MySQL I reference each variable specifically. For instance…

$row = mysql_fetch_array($result, MYSQL_ASSOC

$row[‘name’], $row[‘status’], etc.

But since this one page will be running various reports on the fly it needs to be able to take the data in the mysql_fetch_array and output it. Just basically… whatever and however many fields the SELECT statement grabs from the database, my code needs to be able to process and create a tab-delimited text file from.

I’m also wondering if there is a way to get the field names into the first row, kind of as a header type row. Example…

name status age
Bob M 27
Lisa S 18

Etc.

Suggestions?

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@SyCoSep 26.2008 — This is for MSSQL You can convert it to MySQL easily enough (the SQL functions and SQL select)

It should create file on the fly. If you get errors it's usually a permission thing or make sure the folder is writable.

[code=php]<?
//connect to db
include('db_connect.php');

//set file path
$filename='file.txt';

//clear current contents out of file
//file_put_contents($filename,'');//uncomment if required

//open file for writing (appending)
$fh=fopen($filename,"a");

//Then get you records
$q="select top 10 * from users";
$r=mssql_query($q);

//write the column names
$row=mssql_fetch_assoc($r);
//loop across the columns
foreach($row as $key => $value){
fputs($fh, $key."t");//write the values and tabs
}
fputs($fh, $value."n");//write a newline char

mssql_data_seek($r,0);//reset the result resource

//loop through the rows
while($row=mssql_fetch_assoc($r)){
//loop across the columns for the values
foreach($row as $key => $value){
fputs($fh, $value."t");//write the values and tabs
}
fputs($fh, $value."n");//write a newline char

}
[/code]
Copy linkTweet thisAlerts:
@xvszeroauthorSep 29.2008 — Sweet, had to edit a bit but it works.
×

Success!

Help @xvszero spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...