Jump to content

Recommended Posts

Hey guys, I'm trying to limit my query to 5 results, but TOP is not working and LIMIT obviously does not work (I usually work with MySQL).

 

Here is my query:

$query = "SELECT PERSON.PERSON_ID, PERSON.LAST_NAME, PERSON.FIRST_NAME FROM PERSON where PERSON.LAST_NAME like '%$q%' or PERSON.FIRST_NAME like '%$q%' order by PERSON.LAST_NAME";

Can someone please point me in the right direction for limiting the query to 5 results?

 

Thank you!

~ Sarah

Link to comment
https://forums.phpfreaks.com/topic/287133-using-limit-or-top-in-mssql/
Share on other sites

$query = "SELECT TOP 5 PERSON.PERSON_ID, PERSON.LAST_NAME, PERSON.FIRST_NAME FROM PERSON where PERSON.LAST_NAME like '%$q%' or PERSON.FIRST_NAME like '%$q%' order by PERSON.LAST_NAME";
That should be all you need to do.

 

I have tried both "SELECT TOP 5" and "SELECT TOP (5)". Here is the error that is generated:

Fatal Error:  Uncaught exception 'com_exception' with message '<b>Source:</b> Microsoft OLE DB Provider for SQL Server<br/><b>Description:</b> Line 1: Incorrect syntax near '5'.' in C:\xampp\apps\wordpress\htdocs\autocomplete-search\search.php:9
Stack trace:
#0 C:\xampp\apps\wordpress\htdocs\autocomplete-search\search.php(9): com->execute('SELECT TOP 5 PE...')
#1 {main}
  thrown in

What database software are you using, and what version? Also what functions are you using to connect to the database from PHP?

 

SELECT TOP 5 ... works fine for me. TOP has been supported for as long as I have been using SQL Server (since version 2000).

SQL Server 2000.

 

Here is my connection string: 

$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");

//define connection string, specify database driver
$connStr = "Provider=sqloledb;Data Source=SQLDB;Initial Catalog=PERSONDB;User Id=*****;Password=*****";

$conn->open($connStr); //Open the connection to the database

$query = "SELECT TOP (5) PERSON.PERSON_ID, PERSON.LAST_NAME, PERSON.FIRST_NAME FROM PERSON where PERSON.LAST_NAME like '%$q%' or PERSON.FIRST_NAME like '%$q%' order by PERSON.LAST_NAME";

$rs = $conn->execute($query);

Thank you.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.