8

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?

2
  • 1
    If it's only returning a single row, what does it matter? Commented Jan 9, 2011 at 22:02
  • do you really need everything? (*)? Commented Jan 9, 2011 at 22:07

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

3

You can use this code for select query without using while loop:

$conn is an database connection

$sql = "SELECT * FROM teacher_details";
$row = mysqli_fetch_assoc($conn->query($sql) );
$teacher_name = $row['teacher_name'];

Comments

1

When you use functions like mysql_fetch_array, you're not obligated to iterate. Even, when you do it, you're just getting the result of the next row available, until it returns null:

$query = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($query)) {
    var_dump($row);
}

So, doing this for each row in the query is technically the same:

$query = mysql_query("SELECT * FROM table");

$row = mysql_fetch_array($query)
var_dump($row);
// Array()
$row = mysql_fetch_array($query)
var_dump($row);
// Array()
$row = mysql_fetch_array($query)
var_dump($row);
// null < the "while" statment will stop here

Then, you can call mysql_fetch_array once and that's it.

Good luck!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.