Ben
Ben

Reputation: 362

Query whole database but only print the first row

I would like to query the whole table from the database ive created but only print Title and Summary from the first row, I havent been able to find a way to do this, heres the code i have so far:

<?php
    $con = mysqli_connect( 'localhost', 'root'); 
    // Check connection
    if (mysqli_connect_errno()) {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $result = mysqli_query($con, "SELECT * FROM test.articles ORDER BY Date") or die('Unable to run query:' . mysqli_error($con));     
?>

<?php
    while ($row = mysqli_fetch_array($result)) {
        echo  "<h1>" . $row['Title'] . "</h1>";
        echo  "<p>" . $row['Summary'] . "</p>";
    }
?>

I've tried using mysqli_fetch_row, along with other ways but havent been able to find the solution, thanks.

Upvotes: 0

Views: 346

Answers (2)

Fahim Parkar
Fahim Parkar

Reputation: 31627

Change while to if

This will print only first row...

BUT this is not right way.

Right way would be LIMIT the data

SELECT * FROM test.articles ORDER BY Date LIMIT 1
                                          ^^^^^^^

Upvotes: 2

John Conde
John Conde

Reputation: 219794

Just call mysqli_fetch_array() once (remove your loop):

$row = mysqli_fetch_array($result);
echo  "<h1>" . $row['Title'] . "</h1>";
echo  "<p>" . $row['Summary'] . "</p>";

And if you really only want one row, use a LIMIT clause to limit your results to one row. It will be more performant:

SELECT * FROM test.articles ORDER BY Date LIMIT 1

Upvotes: 1

Related Questions