sof_user
sof_user

Reputation: 709

How can I extract a text from a MySQL database character by character?

I need to extract characters sequentially from a MySQL database up to the desired number (not the whole text which is stored as long text or text at a time). I am using PHP. How can I do that please?

Upvotes: 0

Views: 852

Answers (4)

marcind
marcind

Reputation: 53191

You should use the SQL functionSubstring. The link has a bunch of examples on how to do it. You simply invoke a SQL query just like you would any other in PHP.

Upvotes: 0

Bjarni Sævarsson
Bjarni Sævarsson

Reputation: 176

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substr

mysql> SELECT SUBSTRING('Quadratically',5);
        -> 'ratically'
mysql> SELECT SUBSTRING('foobarbar' FROM 4);
        -> 'barbar'
mysql> SELECT SUBSTRING('Quadratically',5,6);
        -> 'ratica'
mysql> SELECT SUBSTRING('Sakila', -3);
        -> 'ila'
mysql> SELECT SUBSTRING('Sakila', -5, 3);
        -> 'aki'
mysql> SELECT SUBSTRING('Sakila' FROM -4 FOR 2);
        -> 'ki'


<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

// select first 5 characters from full_name column in table Persons
$result = mysql_query("SELECT SUBSTRING(full_name, 1, 5) AS partialName FROM Persons");

while($row = mysql_fetch_array($result))
  {
  echo $row['partialName'];
  echo "<br />";
  }

mysql_close($con);
?> 

Upvotes: 0

RobertPitt
RobertPitt

Reputation: 57278

Simply use SUBSTRING for that.

SELECT SUBSTRING(column,80) as string FROM TABLE

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substr

Upvotes: 1

nickf
nickf

Reputation: 546503

You can use the SUBSTRING or SUBSTR method (they are the same).

mysql> SELECT SUBSTRING('Quadratically',5);
        -> 'ratically'
mysql> SELECT SUBSTRING('foobarbar' FROM 4);
        -> 'barbar'
mysql> SELECT SUBSTRING('Quadratically',5,6);
        -> 'ratica'
mysql> SELECT SUBSTRING('Sakila', -3);
        -> 'ila'
mysql> SELECT SUBSTRING('Sakila', -5, 3);
        -> 'aki'
mysql> SELECT SUBSTRING('Sakila' FROM -4 FOR 2);
        -> 'ki'

Upvotes: 0

Related Questions