Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL/SQL retrieve first 40 characters of a text field?

Tags:

sql

php

mysql

How can I retrieve a text field from mysql db table, but not the entire text, just the few 40 or so characters.

Can this be done in sql or do I need to do it using php?

basically what I am trying to do is show the first x characters and then let the user click on that to view the full content.

like image 795
John Avatar asked Jan 17 '10 11:01

John


People also ask

How do I select the first 10 characters in SQL?

SQL Server LEFT() Function The LEFT() function extracts a number of characters from a string (starting from left).

How do I find characters in MySQL?

MySQL SUBSTR() function MySQL SUBSTR() returns the specified number of characters from a particular position of a given string. SUBSTR() is a synonym for SUBSTRING(). A string from which a substring is to be returned. An integer indicating a string position within the string str.


1 Answers

SELECT LEFT(field, 40) AS excerpt FROM table(s) WHERE ... 

See the LEFT() function.

As a rule of thumb, you should never do in PHP what MySQL can do for you. Think of it this way: You don't want to transmit anything more than strictly necessary from the DB to the requesting applications.


EDIT If you're going to use the entire data on the same page (i.e., with no intermediate request) more often than not, there's no reason not to fetch the full text at once. (See comments and Veger's answer.)

like image 76
jensgram Avatar answered Oct 04 '22 06:10

jensgram