Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query without loop

I want to query from the db records for a single post (title, body, date)

For example I have my query..

$query = 'SELECT * FROM posts WHERE id=$post_id';

From that query how can I echo the title for instance without a while or foreach loop?

like image 715
CyberJunkie Avatar asked Jan 09 '11 21:01

CyberJunkie


2 Answers

You can just call mysql_fetch_assoc() (or any similar function) one. Like this:

$sql = "SELECT * FROM table";
$row = mysql_fetch_assoc( mysql_query($sql) );
echo $row['title'];

This is the easiest and most readable way to do this with the MySQL functions.

like image 54
Richard Tuin Avatar answered Oct 06 '22 00:10

Richard Tuin


You can use mysql_result:

$sql = 'SELECT * FROM posts WHERE id=$post_id';
$query = mysql_query($sql);
echo mysql_result($query, 0, 'title');

This will echo the field titlefor the first(0) row.

like image 22
alexn Avatar answered Oct 06 '22 00:10

alexn