James Programmer James Programmer - 3 months ago 6
PHP Question

PHP and MYSQL Database Retrieving

$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "register";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> email: " . $row["email"] . "<br>";
}
}


I am trying to get only the last row and the email column. The method that I am doing takes every row, with the email column. If somebody could adjust my code and comment it, I would really appreciate it.

Answer

You want to

  • To get the LAST row sort the results descending on a fields that gets incremented with every new row like the auto increment field [I am assuming that id] ( ORDER BY id DESC)

  • limit the rows returned to 1 ( LIMIT 1 )

So try this query instead

SELECT email FROM users ORDER BY id DESC LIMIT 1

In your code

$sql = "SELECT email FROM users ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo "<br> email: " . $row["email"] . "<br>";
}