Ad

How To Split Range Of Number And Calculate Total Range?

- 1 answer

I want to fetch page range from my DB column pages from table articles

|article_id|pages|

    1       41-47
    2       60-61

which the output is for article id 1:

<fpage>41</fpage>
<lpage>47</lpage>

and here is my code:

$page = mysqli_query($con,"SELECT pages FROM articles WHERE article_id='1'")  or die(mysql_error());

while($page2=mysqli_fetch_array($page))
 {
    result = preg_replace_callback('/(\d+)-(\d+)/', function($m)
   {
        return implode(',', range($m[1], $m[2]));
    }, $page2);

    $page3 = explode(',', $result['pages']);
    $xml .= '<fpage>'.$page3[0].'</fpage>';
    $xml .= '<lpage>'.$page3[6].'</lpage>';

}

I manage to get for lastpage of article 1 using array [6]. So how to do for the article that might have different range? And also, I want to calculate the page range ,

for article 1 the total page range (41-47) is 6, but I don't know how to do it. Your Help is much appreciated. Thanks :)

Ad

Answer

Use SUBSTRING_INDEX() function to split the string:

Try this:

SELECT SUBSTRING_INDEX(pages, '-', 1) AS fpage, 
       SUBSTRING_INDEX(pages, '-', -1) AS lpage, 
      (SUBSTRING_INDEX(pages, '-', -1) - SUBSTRING_INDEX(pages, '-', 1)) AS pageRange
FROM articles 
WHERE article_id = '1';
Ad
source: stackoverflow.com
Ad