im after the simplest (and easiest to understand from a novice programmers perspective) to do the following;
I have a query on a database:
$newsquery = mysql_query('SELECT * FROM news ORDER BY id DESC LIMIT 3');
I want to to select the top three rows in my table and get the column 'news'
Then I need to save each result as a separate variable, this could be $news1, $news2 and $news3
So i could then use these variables to echo as needed on my page.
I hope this makes sense, many thanks .
stop using mysql
as PHP
is removing it at the end of the year,use PDO
or mysqli
$rows = array();
while($row = mysql_fetch_assoc($newsquery)) {
$rows[] = $row['news'];
}
$news1 = $rows[0];
$news2 = $rows[1];
$news3 = $rows[2;
with PDO
$rows = $results->fetchAll(PDO::FETCH_ASSOC);
$news1 = $rows[0]['news'];
$news2 = $rows[1]['news'];
$news3 = $rows[2]['news'];
Since you used mysql
, I will give the answer in mysql itself.
$newarray = array();
$newsquery = mysql_query('SELECT * FROM news ORDER BY id DESC LIMIT 3');
while( $row = mysql_fetch_assoc( $newsquery ))
{
$new_array[] = $row; // Inside while loop
}
OR use the below code
$newarray = array();
$newsquery = mysql_query('SELECT * FROM news ORDER BY id DESC LIMIT 3');
while ($row = mysql_fetch_array($newsquery))
{
$new_array[$row['newsid']]['newsid'] = $row['newsid'];
$new_array[$row['newsid']]['data'] = $row['data'];
}
To get each column value
foreach($new_array as $array)
{
echo $array['newsid'].'<br />';
echo $array['data'].'<br />';
}