/    Sign up×
Community /Pin to ProfileBookmark

Storing while loop results in a variable?

Hi!

I’m currently retrieving and displaying results from my sql table using the following:

[code=php]
<?

$sql = “SELECT * FROM news”;
$res = mysql_query($sql);

while ($row = mysql_fetch_array($res)) {
echo ‘<div class=”news-title”>’ . $row[1] . ‘</div>’;
echo ‘<div class=”news-date”>’ . $row[2] . ‘</div>’;
}

?>
[/code]

However, I’m keen to store all the data outputted from this query in a single variable.
Would I have to use arrays, or is there an easy way of doing this?

Many thanks.

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiJan 19.2009 — You could just concatenate the data using a certian character or set of characters:

[code=php]
$data = '';
while ($row = mysql_fetch_array($res)) {
$data .= implode(' ', $row) . ' ';
}
$data = trim($data);
[/code]


but it depends what you are then going to do with the data. It's more usual to store the data in an array:

[code=php]
$data = array();
while ($row = mysql_fetch_array($res)) {
$data[] = $row;
}
[/code]


But again it is really dependant on what you're trying to achieve.
Copy linkTweet thisAlerts:
@invisionauthorJan 19.2009 — Hi Mindzai.

Many thanks for the speedy reply.

I'm basically going to take the data, then use it in an include file so it outputs HTML like:

<div class="news-title">News Title 1</div>

<div class="news-date">20/12/1980</div>

<br />

<div class="news-title">News Title 2</div>

<div class="news-date">20/12/1981</div>

...
Copy linkTweet thisAlerts:
@MindzaiJan 19.2009 — OK then the following should work (assuming $row[1] and $row[2] are the correct columns):

[code=php]
$data = '';
while ($row = mysql_fetch_array($res)) {
$data .= '<div class="news-title">' . $row[1] . "</div>n";
$data .= '<div class="news-date">' . $row[2] . "</div>n";
}
[/code]
Copy linkTweet thisAlerts:
@invisionauthorJan 19.2009 — Brilliant Mindzai - that worked a treat! Many thanks, it was fairly easy in the end, I guess ?
Copy linkTweet thisAlerts:
@MindzaiJan 19.2009 — Everything's easy once you know the answer ?
×

Success!

Help @invision 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.25,
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,
)...