PDA

View Full Version : Echo individual records using hardcoded ID numbers?


arc2002
02-03-2005, 09:53 AM
Hi there,
I have a little problem I would really appreciate some help.

I have an SQL database, which looks like this;
ID - News
1 - News item 1
2 - News item 2

And I am trying to display them on a page, using echo. However what i am trying to do is to display them individually, eg echo id=2 in one place on the page, then echo id=1 somewhere else. I am really not too sure how to do this!

I will post the PHP code;
<?php
mysql_select_db($database_wiserhosting, $wiserhosting);
$query_Recordset1 = "SELECT * FROM database WHERE id = 1";
$Recordset1 = mysql_query($query_Recordset1, $wiserhosting) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>

<?php echo $row_Recordset1['news']; ?>

<?php
mysql_free_result($Recordset1);
?>

However my problem is this code simply displays record 1, and was wondering if the only way to do it is to create another recordset?

Would appreciate any help Cheers Bob.

chump2877
02-03-2005, 01:08 PM
However what i am trying to do is to display them individually, eg echo id=2 in one place on the page, then echo id=1 somewhere else.

I could be missing something here, but why don't you just perform multiple queries for your different news articles? One quuery can display one article, and then another database query can display a second article, perhaps further down the page....

arc2002
02-03-2005, 03:22 PM
Yes thats what i am trying to do. However i was wondering if there was anyway to have one database query, but select the news item id when you echo.
Thanks for your help, i am just looking for a more elegant way of doing it.
Cheers

firepages
02-03-2005, 05:08 PM
<?php
mysql_select_db($database_wiserhosting, $wiserhosting);
$query = "SELECT * FROM database LIMIT 10";//just get 10 records
$resource = mysql_query($query , $wiserhosting) or die(mysql_error());
while( $r = mysql_fetch_assoc( $resource ) ){
$row[$r['id']] = $r ;//add all the records to an array
}
?>

<b>News from record 1</b><br />
<?echo $row[1]['news'];?>
<p />
<b>News from record 5</b><br />
<?echo $row[5]['news'];?>
etc


loading everything into an array as above is fine for small recordsets , you would not want to load 1000 rows like this (which is why I used LIMIT 10 here) , also if you are storing the data this way its more important than normall to just select the fields you really want (e.g SELECT id,news,other_field FROM table) as opposed to *

note that the call to mysql_num_rows is pointless in your original code since the result only ever fetches one record.