Home » Php » php – query without loop

php – query without loop

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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.

Answer:

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.

Answer:

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'];

Answer:

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!