English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I got this code that has to get the last news from the database and print it but the output is weird an instead of printing the last new it prints: "Resource id #4"
anybody knows whats wrong with this code?

mysql_connect ('localhost' , 'root' , '');
mysql_select_db ('db2');
$data = mysql_query ("SELECT * FROM news");
$rowsnum = mysql_num_rows ($data);
$news1 = mysql_query ("SELECT new FROM news WHERE id = '$rowsnum'");
echo $news1;

2006-06-08 03:10:43 · 3 answers · asked by aryaxt 3 in Computers & Internet Programming & Design

I have the databass and when i get the number of the rows its exactly the same as number of the rows in database so theres nothing wrong with connecting to the database and getting the information

2006-06-08 03:28:39 · update #1

thx M. raja it fixed my problem but i still dont understand wat was wrong with my code lol.
doesnt matter it works now :)

2006-06-08 03:54:59 · update #2

3 answers

everything is correct, but "rowsnum'" not an id in the table. Instead of this you can use maxid.

mysql_connect ('localhost' , 'root' , '');
mysql_select_db ('db2');
$news1 = mysql_query ("SELECT new FROM news WHERE id =(select max(id) from news)";
$row=mysql_fetch_array($news1);
$newslast=$row['new'];
echo $newslast;

Please try this code

2006-06-08 03:49:37 · answer #1 · answered by M.Raja 2 · 2 0

An improvment on that last bit...

...
$news = mysql_query("SELECT * FROM news ORDER BY id DESC LIMIT 1");
echo mysql_result($news,0);

This assumes id is an auto_increment value.

This method is more efficient because there is no WHERE clause so MySQL doesn't have to do any comparisons. It just sorts them based on id (which should be the primary key or at least indexed), grabs the latest one (LIMIT 1) and then instead of mysql_fetch_array(), you just use mysql_result with 0 as the row index (since we only pulled one value).

2006-06-13 07:03:54 · answer #2 · answered by Jody 3 · 0 0

Did you setup the database??

what is the program ??

2006-06-08 03:26:35 · answer #3 · answered by Rusty Nails 5 · 0 0

fedest.com, questions and answers