How can I extract a text from a MySQL database character by character?
I need to extract characters sequentially f开发者_如何学Crom 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?
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
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);
?>
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'
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.
精彩评论