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 .

3
  • Is SELECT TOP 1 valid for mysql? Commented Jun 23, 2019 at 7: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 Commented Jun 23, 2019 at 7: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. Commented Jun 23, 2019 at 8:20

2 Answers 2

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;

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

Comments

0

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

$sql = "SELECT * FROM data ORDER by id DESC LIMIT 1"; 

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.