How to Select First Row Only in PHP MySQL?

03-Apr-2023

.

Admin

How to Select First Row Only in PHP MySQL?

Hi Dev,

This is a short guide on how to select first row only in php mysql. I would like to share with you select first row of database sql with code examples. it's simple example of display only first row mysql using php. you will learn php and mysql select first row only.

To return only the first row that matches your SELECT query, you need to add the LIMIT clause to your SELECT statement.

Example :


index.php

$sql = CREATE TABLE students (

id int NOT NULL AUTO_INCREMENT PRIMARY KEY,

name varchar(20),

subject varchar(20),

gender varchar(20)

);

Insert some records in the table using insert command :

$sql = INSERT INTO students (name, subject, gender) VALUES('Mark', 'Math', 'male');

$sql = INSERT INTO students (name, subject, gender) VALUES('Sarah', 'English', 'female');

$sql = INSERT INTO students (name, subject, gender) VALUES('Nathan', 'English', 'male');

Display all records from the table using select statement :

select * from students;

Output:

+-----------+-------------+------------+

| Id | Name | subject | gender |

+-----------+-------------+------------+

| 1 | Mark | Math | male |

| 2 | Sarah | English | female |

| 3 | Nathan | English | male |

+-----------+-------------+------------+

To return only the first row, you need to execute the following SQL query:

SELECT * FROM students LIMIT 1;

Output:

+-----------+-------------+------------+

| Id | Name | subject | gender |

+-----------+-------------+------------+

| 1 | Mark | Math | male |

+-----------+-------------+------------+

I hope it could help you...

#PHP