0

I am new to programming. I wrote a code to fetch last added record but it throwing an error.

Notice: Trying to get property of non-object in C:\xampp\htdocs\fetch.php on line 17 0 results

fetch.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "d4rky";

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

$sql = "SELECT TOP 1 * FROM data ORDER by id DESC LIMIT 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"]. " - Name: " . $row["dataset"]. " " . $row["datamet"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

Table name : data

Thanks in advance .

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Is `SELECT TOP 1` valid for mysql? – Nigel Ren Jun 23 '19 at 07:31
  • You are using `SQL Server / MS Access Syntax` inside mysql which is wrong, you can use `SELECT * FROM data ORDER by id DESC LIMIT 1` – Rakesh Jakhar Jun 23 '19 at 07:37
  • The main problem is that you assume your sql query is correct and you do not check for errors. Had you done so, you would know what went wrong with your code. – Shadow Jun 23 '19 at 08:20

2 Answers2

1

It seems that you are mixing sql server syntax with mysql.

SELECT TOP 1 is used in sql server. In mysql you have to use Limit to get specific number of records like.

SELECT field1,fileld2,field3 FROM table_name ORDER BY id DESC LIMIT 1;

OR to fecth all fields simply use

SELECT * FROM table_name ORDER BY id DESC LIMIT 1;

M Ikram Zafar
  • 150
  • 1
  • 3
  • 13
0

You can not use SQL syntax in MYSQL, change your query to

$sql = "SELECT * FROM data ORDER by id DESC LIMIT 1";
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20