PHP Error: Undefined offset: 10 - php

I wrote a program that creates a puzzle based on user's inputs. There is a html form that accepts the user's words and posts them to the php program. Then the php program creates the puzzle and prints it.
There is a live demo here. You can type you own words.
It looks good but when I run it in my local server with php error prompt turned on, I see the error msg saying Undefined offset: 10 at line 147 and 148. The error is generated from the php code line starting from if ($board[$curr_row][$curr_col] == '.'... You can use Ctrl+F to find the code. I don't understand how could I get 10 in $curr_col or $curr_row since the loop should stop after they reach 9.
Please help me understand how could the loop run after they have reached 10, thanks a lot!
The zipped version of the program is here.
Here is the code of the php:
<html>
<body>
<?php
/* word Find
Generates a word search puzzle based on a word list entered by user.
User can also specify the size of the puzzle and print out
an answer key if desired
*/
//If there is no data from the form, prompt the user to go back
if (!filter_has_var(INPUT_POST, "puzzle_name")) {
print <<<MUL_LINE
<!DOCTYPE html>
<html >
<head>
<title>Oops!</title>
</head>
<body>
<p>This page should not be called directly, please visit
the puzzle form to continue.</p>
</body>
</html>
MUL_LINE;
} else {
$boardData = array("name" => filter_input(INPUT_POST, "puzzle_name"), "width" => filter_input(INPUT_POST, "grid_width"), "height" => filter_input(INPUT_POST, "grid_height"));
if (parseList() == TRUE) {//parse the word list in textarea to an array of words
//keep trying to fill the board untill a valid puzzle is made
do {
clearBoard();
//reset the board
$pass = fillBoard();
} while($pass == FALSE);
printBoard();
//if the board if successfully filled, print the puzzle
}
}//end word list exists if
//parse the word list in textarea to an array of words
function parseList() {
//get word list, creates array of words from it
//or return false if impossible
global $word, $wordList, $boardData;
$wordList = filter_input(INPUT_POST, "wordList");
$itWorked = TRUE;
//convert word list entirely to upper case
$wordList = strtoupper($wordList);
//split word list into array
$word = explode("\n", $wordList);
//an array of words
foreach ($word as $key => $currentWord) {
//trim all the beginning and trailer spaces
$currentWord = rtrim(ltrim($currentWord));
//stop if any words are too long to fit in puzzle
if ((strlen($currentWord) > $boardData["width"]) && (strlen($currentWord) > $boardData["height"])) {
print "$currentWord is too long for puzzle";
$itWorked = FALSE;
}//end if
$word[$key] = $currentWord;
}//end foreach
return $itWorked;
}//end parseList
//reset the board by filling each cell with "."
function clearBoard() {
//initialize board with a . in each cell
global $board, $boardData;
for ($row = 0; $row < $boardData["height"]; $row++) {
for ($col = 0; $col < $boardData["width"]; $col++) {
$board[$row][$col] = ".";
}//end col for loop
}//end row for loop
}//end clearBoard
//fill the board
function fillBoard() {
global $word;
$pass = FALSE;
//control the loop of filling words, false will stop the loop
//control the loop, if all the words are filled, the counter will be as equal to the number
//of elements in array $words, thus the loop stops successfully
$counter = 0;
do {
$pass = fillWord($word[$counter]);
//if a word is filled, $pass is set to true
$counter++;
}
//if a word can't be filled, pass==FALSE and loop stops
//or if all words are through, loop stops
while($pass==TRUE && $counter<count($word));
//return TRUE if all filled successfully, FALSE if not
if ($pass == TRUE && $counter == count($word)) {
return TRUE;
} else {
return FALSE;
}
}
//function used to fill a single word
function fillWord($single_word) {
global $board, $boardData;
//the direction of how the word will be filled, 50% chance to be H, and 50% chance to be V
$dir = (rand(0, 1) == 0 ? "H" : "V");
//H(horizontal) means fill the word from left to right
//V(vertical) means fill the word from up to down
//loop control. if a letter is not filled, $pass is set to false and loop stops
$pass = TRUE;
//loop control. if all letters are filled successfully, loop stops too.
$counter = 0;
//decide the cell to fill the first word. the cell is located at $board[$curr_row][$curr_col]
if ($dir == "H") {//if the word will be fileld from left to right
$curr_row = rand(0, $boardData["height"] - 1);
//pick up a random row of the 10 rows ( rand(0,9) )
$curr_col = rand(0, ($boardData["width"] - ( strlen($single_word - 1)) - 1));
//pick up a random column of fillable columns
//if the word is "banana" and the board's width
//is 10, the starting column can only be rand(0, 4)
} else if ($dir == "V") {//if the word will be fileld from up to down
$curr_row = rand(0, ($boardData["height"] - ( strlen($single_word - 1)) - 1));
$curr_col = rand(0, $boardData["width"] - 1);
} else {
print "invalid direction";
}
//the loop that keeps trying to fill letters of the word
while ($pass && ($counter < strlen($single_word))) {//while the $pass is true AND there are still letters
//to fill, keep the loop going
//the next line and the line after generate the msg "Undefined offset: 10",
//$curr_row and $curr_col should never be 10 because the loop should be stopped
//if the last letter of the word is filled
if ($board[$curr_row][$curr_col] == '.' || //if the cell is not filled, reset fillboard() to "."
$board[$curr_row][$curr_col] == substr($single_word, $counter, 1))//or it has already been filled with the same letter
{
$board[$curr_row][$curr_col] = substr($single_word, $counter, 1);
// write/fill the letter in the cell
$counter++;
if ($dir == "H") {
$curr_col++;
//next column, move to the next right cell
} else if ($dir == "V") {
$curr_row++;
//next row, move to the next lower cell
} else {
print "\nHuge direction error!";
}
} else {
$pass = FALSE;
// failed to fill a letter, stop the loop
}
}
//if all the letters are filled successfully, the single word is filled successfully
//return true, let $fillBoard go filling next single word
if ($pass && ($counter == strlen($single_word))) {
/* for debug purpose
print "<hr />";print "<p>TRUE</p>";print "<hr />";
print $single_word;
print $curr_row . "," . $curr_col . "<br />";
print "<hr />";*/
return TRUE;
} else {
//failed to fill the word, reset the board and start all over again
return FALSE;
}
}//end function fillWord
//print the successful filled puzzle
function printBoard() {
global $board;
print <<<MULLINE
<style type="text/css">
table, td{
border: 1px solid black;
}
</style>
MULLINE;
print '<table >';
foreach ($board as $row) {
print '<tr>';
foreach ($row as $cell) {
print '<td>';
print $cell;
print '</td>';
}
print("<br />");
print '</tr>';
}
print "</table>";
}
?>
</body>
</html>

I don't think the following fragment of code is right.
strlen($single_word - 1)
located in the lines:
$curr_col = rand(0, ($boardData["width"] - ( strlen($single_word - 1)) - 1));
and
$curr_row = rand(0, ($boardData["height"] - ( strlen($single_word - 1)) - 1));
It will convert the word to an integer. Subtract one from that number. Then convert that back to a string and take the length. So you have a rubbish value for the length.

Related

Show In article ads every x amount of words repeatedly?

I have a code that shows in-article ads after a specified amount of words, the thing is:
If I write a very long article, the ad will be lost due to text length, so there will be only text showing. What I need to do is to create 1 or 2 ads and make it/them repeat indefinitely every 4 paragraphs and 250 words (just an example), based on article length.
HERE'S AN EXAMPLE:
This blog has the very same thing that I'm trying to achieve. As you scroll the article, you'll see that more and more ads will be loaded between the article paragraphs.
THIS IS MY CURRENT CODE:
// Insert ads after a number of words and after the </p> closing tag.
// https://stackoverflow.com/questions/42801541/insert-text-in-content-after-300-words-but-after-closing-tag-of-a-paragraph
function anunciamentosegundo($content) {
$ad_code = '<script type="application/javascript">Adsense code goes here</script>';
// only inject google ads if post is longer than 800 characters
$enable_length1 = 1800;
// Insert at the end of the paragraph every 200 words
$after_word1 = 400;
// Maximum of 2 ads
$max_ads = 2;
if (strlen($content) > $enable_length1) {
$len = strlen($content);
$i=0;
// Keep adding untill end of content or $max_ads number of ads has ben inserted
while($i<$len && $max_ads-->0) {
// Work our way untill the apropriate length
$word_cout = 0;
$in_tag = false;
while(++$i < $len && $word_cout < $after_word1) {
if(!$in_tag && ctype_space($content[$i])) {
// Whitespace
$word_cout++;
}
else if(!$in_tag && $content[$i] == '<') {
// Begin tag
$in_tag = true;
$word_cout++;
}
else if($in_tag && $content[$i] == '>') {
// End tag
$in_tag = false;
}
}
// Find the next '</p>'
$i = strpos($content, "</p>", $i);
if($i === false) {
// No more paragraph endings
break;
}
else {
// Add the length of </p>
$i += 4;
// Get ad as string
ob_start();
echo $ad_code ; //would normally get printed to the screen/output to browser
$ad = ob_get_contents();
ob_end_clean();
$content = substr($content, 0, $i) . $ad . substr($content, $i);
// Set the correct i
$i+= strlen($ad);
}
}
}
return $content;
}
add_filter( 'the_content', 'anunciamentosegundo' );
Currently I can show ads after an amount of words and paragraphs, but not every x amount words and paragraphs. What should I do?

Php: Delete string from text file [duplicate]

This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
I need to delete a specific string set from a txt file. Currently, the code works in a similar manner to post the data directly to the file. However, trying to remove the same data, inputted in the same manner, will not allow it. In it's current state, the code looks like this for the string removal.
We were NOT allowed to use prebuilt sorting functions or use functions like str_replace or similar code.
Here is the current code for the string removal:
$blankReplace = "";
$found = false;
$fileData = file($fileInput,FILE_IGNORE_NEW_LINES);
for($i = 0; ($i < count($fileData)) && != $found; $i ++)
{
if($fullNameAndEmail == $fileData[$i])
{
$pos = $i;
$name = $fileData[$i];
$found = true;
}
}
if($found == true)
{
// Exit path. Go to for($j = 0) path
unset($fileData[$pos]);
shuffle($fileData);
}
else
{
//Error Msg
}
$writeToFile = fopen($inputFile,'w+');
for($j = 0;$j<count($fileData);$j++)
{
if(trim($fileData[$j]) != " ")
{
$rewrittenList = trim($fileData[$j])."\n";
fwrite($writeToFile, $rewrittenList);
}
}
The code outputs an error of T_IS_NOT_EQUAL in code upon researching the error. The data comes in as direct data from the file() read, so it should work. The error is pointing at for($i = 0; ($i < count($fileData)) && != $found; $i ++) line currently, but likely also references a similar occurrence in the code.
The data is inputted in the format:
firstname lastname emailaddress
I also need to be able to handle if multiple instances of the mentioned name occur so say we have:
Matt Person emailaddr#email.com
Matt Person emailaddr#email.com
That it will delete one instance, and not all, in cases similar to this.
Any help is appreciated, Thank you for your time in advance.
EDIT:
Example input:
Matthew person person#email.com
John holton person#email.com
Person Name person#gmail.com
The user will input a person's name (in format above) and it will result in removing a person. Say they input into the form:
$fullName = "Matthew person";
$emailAddr = "person#email.com";
The output will edit the data to put the data into a single line again
$fullNameAndEmail = $firstName." ".$lastName." ".$emailAddr;
The output of the code, in this example will remove "Matthew person person#email.com"
So the output in the text file will output:
John holton person#email.com
Person Name person#gmail.com
Edit 2: Code in it's current state
<!doctype HTML>
<html>
<meta charset="utf-8">
<head>
<title>Updating the guest book!</title>
</head>
<body>
<?php
$fileInput = "guestBook.txt";
$fileInputInData = file_get_contents($fileInput); // Gets data from file
$testBool = file_exists($fileInput);
$fullName = trim($_POST["fullName"]);
$emailAddr = trim($_POST["emailAddr"]);
$fileSize = filesize($fileInput);
if(!empty($fullName) and !empty($emailAddr))
{
if($testBool == 0)
{
echo "There was an issue with the file. Please have it checked.</br>";
}
else
{
echo "Made it into else path for testBool </br>";
if($fileSize > 0)
{ #code for truth
echo "Made it into filesize check. Filesize: $fileSize </br>";
$fullNameLen = strlen($fullName);
$emailAddrLen = strlen($emailAddr);
$fullNameArr = explode(" ", $fullName);
$firstName = trim($fullNameArr[0]);
$lastName = trim($fullNameArr[1]);
$fullNameToWrite =$firstName." ".$lastName;
$emailAddrCheck=substr_count($emailAddr, "#");
if ($emailAddrCheck == 1)
{
echo "Email address check passed</br>";
#email addr entered right path
$fullNameAndEmail =$fullNameToWrite." ".$emailAddr." has signed in.\n";
$inputFile = "guestBook.txt";
//$pos = strpos($writeToFile, $fullNameAndEmail);
//$writeToFileEx = explode("\n", $fileInputInData);
$blankReplace = "";
$str = $fileInputInData;
$find = $fullNameAndEmail;
$arr=explode("\n", $str);
Foreach($arr as $key => &$line)
{
If($line == $find)
{
Unset($arr[$key]);
shuffle($arr);
}
}
$writeToFile = fopen($inputFile,'w+');
$rewrittenList = trim($arr)."\n";
fwrite($writeToFile, $rewrittenList);
fclose($inputFile);
}
else {
echo "Email address check failed. Invalid email address entered. </br>
Line 55 occured.</br>";
#email addr entered wrong message
}
//asort(array) sorts array low to high (ascending)
//arsort(array) sorts array high to low (descending)
}
else
{
echo "Did not make it into filesize check. Filesize: $fileSize. Line 63 occured </br>";
}
}
}
else if (empty($fullName) or empty($emailAddr))
{
echo "Error! Line 23: One of the inputs was left empty. Line 69 occured </br>";
}
else
{
echo "Error! Line 23: Did not detect any values in either data area,</br>and program
did not go into first error. Line 73 occured </br>";
}
?>
<br>
</body>
</html>
I think you have overcomplicated it.
I foreach each line and check if it matches.
If it does I unset the line.
After the loop I implode on new line and the string is back to normal but without the $find's.
$str = "Matt Person emailaddr#email.com
John doe doesoe#gmail
Matt Person emailaddr#email.com
Trump donald#whitehouse";
$find = "Matt Person emailaddr#email.com";
$arr=explode("\n", $str);
Foreach($arr as $key => &$line){
If($line == $find){
Unset($arr[$key]);
}
}
Echo implode("\n", $arr);
https://3v4l.org/hmSr7

Generating a Non-Repeating Random Number - PHP

I'm trying to get a custom function in php to return a random number between 1 and 20 that does not repeat i.e. produce the same number more than once, since I need to subsequently use this number to navigate to one of twenty web pages, and I don't want the same web page displayed.
Here is my code in three steps:
<form action="rand.php">
<p>Click this button to display a random number that does not repeat...</p>
<p><input type="submit" value="Generate"></p>
</form>
Here is rand.php:
require_once('functions.php');
$page = generateNumber();
echo $page;
Here is functions.php:
<?php
$check = array();
function generateNumber() {
global $check;
$page_no = mt_rand(1,20);
$check[] = $page_no;
if (count($check) != 1) {
foreach ($check as $val) {
if ($val == $page_no) {
$page_no = mt_rand(1,10);
continue;
}
}
return $page_no;
}
else {
return $page_no;
}
}
?>
My code seem to be functioning, however, it is repeating numbers so I am obviously doing something wrong. The reason I initially check the count is so that is returns the first number regardless, since it would be a single fresh number.
In order to see the number change I have been refreshing the rand.php page in my browser.
I would keep it simple.
// List numbers 1 to 20
$pages = range(1,20);
// Shuffle numbers
shuffle($pages);
// Get a page
$page = array_shift($pages);
In order to go through all the 20 numbers on each page visit, without repeating, you will need to set a session variable.
<?php
session_start();
if (!isset($_SESSION['numbers'])) {
$_SESSION['numbers']="*"; //---create the session variable
}
function get_number() {
$i = 0;
do {
$num=rand(1,20); //---generate a random number
if (!strstr($_SESSION['numbers'],"*".$num."*")) { //---check if the number has already been used
$_SESSION['numbers']=$_SESSION['numbers'] . $i . "*"; //---add the number to the session variable to avoid repeating
if (substr_count($_SESSION['numbers'],"*")>=21) { //---resets the session variable when all 20 number have been used
$_SESSION['numbers']="*";
}
$i=$num; //---ends the while loop to return the value
}
} while ($i==0);
return $i;
}
?>

Finding all points contouring the overlapping squares

The setup:
a. 2D surface
b. points (with x, y coordinates) which when connected form squares.
c. I found an algorithm that finds the intersection points of those squares so assume we have them as well.
The question is: how do I get points that contour the squares.
I've included an image for better understanding.
I was looking into http://en.wikipedia.org/wiki/Convex_hull_algorithms but it seems like they all skip those intersections (the 90' angles).
I am writing this in php but i'd love to even see a pseudo code if at all possible.
<?php
//WARNING! we assume coords as non-polar. for this to work on large-scale, you need to convert polar into decard coords.
//Can be done outside this script.
//Points sample:
$points_raw=json_decode('{"1":[[41.014357690351,-73.73715475406],[41.029170309649,-73.73715475406],[41.014357690351,-73.75644124594],[41.029178309649,-73.73721675406],[41.014365690351,-73.75650324594],[41.031554690351,-73.73806375406],[41.046091309649,-73.78489424594],[41.014688690351,-73.78819424594],[41.012691690351,-73.75993275406],[41.012691690351,-73.77921924594],[41.015809690351,-73.75893475406],[41.053689309649,-73.76006575406],[41.053689309649,-73.77935224594],[41.050793309649,-73.78376624594],[41.043862309649,-73.79638424594],[41.029049690351,-73.79638424594],[41.019350690351,-73.79608224594],[41.033268690351,-73.73637875406],[41.048081309649,-73.73637875406],[41.048081309649,-73.75566524594],[41.014365690351,-73.75644124594],[41.029170309649,-73.73721675406],[41.018165690351,-73.75650324594],[41.029178309649,-73.74662775406],[41.031554690351,-73.74662775406],[41.033268690351,-73.73806375406],[41.043862309649,-73.78489424594],[41.019350690351,-73.78819424594],[41.015809690351,-73.75993275406],[41.014688690351,-73.77921924594],[41.018165690351,-73.75893475406],[41.047266309649,-73.76006575406],[41.050793309649,-73.77935224594],[41.046091309649,-73.78376624594],[41.029049690351,-73.79608224594],[41.047266309649,-73.75566524594]]}',1);
//BEGIN HERE:
$points=$points_raw[1];
function to_round($val)
{
//here we can try conversion from polar to decard. not sure if will work
//no conversion for now, but just rounding for comparsion
return round($val*1000000000000);
}
function sort_points_array($a, $b, $which)
{
$da=to_round($a[$which]);
$db=to_round($b[$which]);
if ($da == $db) {
return 0;
}
return ($da < $db) ? -1 : 1;
}
function sort_by_0($a, $b)
{
return sort_points_array($a, $b, 0);
}
function sort_by_1($a, $b)
{
return sort_points_array($a, $b, 1);
}
//BEGIN OF UNOPTIMIZED SORT
//sort by columns from left to right (does not have to be left/right on the map)
//but we will try :) 0 -> Y, 1 -> X
//sort by X, so lower X will be on top of array.
//and each point in those columns will be also sorted from top to bottom by their Y
usort($points,"sort_by_1");
//then foreach to split array by "columns";
$column_counter=0;
$point_columns=array();
$point_columns[$column_counter][]=$points[0];
foreach($points as $n_point=>$p_coords)
{
if($n_point>0)
{
if(to_round($p_coords[1]) > to_round($point_columns[$column_counter][1][1]))
$column_counter++;
$point_columns[$column_counter][]=$p_coords;
}
}
//now sort each column
$sorted_point_columns=array();
foreach($point_columns as $pcn => $p_column)
{
usort($p_column,"sort_by_0");
$sorted_point_columns[$pcn]=$p_column;
}
//SAME TO MAKE sorted_point_rows
usort($points,"sort_by_0");
$row_counter=0;
$point_rows=array();
$point_rows[$row_counter][]=$points[0];
foreach($points as $n_point=>$p_coords)
{
if($n_point>0)
{
if(to_round($p_coords[0]) > to_round($point_rows[$row_counter][0][0]))
$row_counter++;
$point_rows[$row_counter][]=$p_coords;
}
}
$sorted_point_rows=array();
foreach($point_rows as $prn => $p_row)
{
usort($p_row,"sort_by_1");
$sorted_point_rows[$prn]=$p_row;
}
// END OF UNOPTIMIZED SORT
//output array
$final_points_poly=array();
//clearly first point will be from 1st row;
//and we will go to the RIGHT in current row to find next point
$final_points_poly[0]=$sorted_point_rows[0][0];
//and let the magic begin:
$finished=false;
$last_point_index=0;
$points_total=count($points);
$pos_x=0; //pos by columns
$pos_y=0; //pos by rows
$relative_X=0; //relative X position in current ROW;
$relative_Y=0; //relative Y position in current COLUMN;
$rule=1; // right / down = 1, left / up = -1
//detect if we go by X or Y
$going_Y=false;
$finished=false;
while(!$finished)
{
if($going_Y)
{
$relative_Y+=$rule;
$last_point_index+=1;
$cur_p=$sorted_point_columns[$pos_x][$relative_Y];
$final_points_poly[$last_point_index]=$cur_p;
$going_Y = !$going_Y;
//search for pos_y:
foreach($sorted_point_rows as $cur_y => $row)
{
if(to_round($row[0][0]) == to_round($cur_p[0]))
{
$pos_y=$cur_y;
//search for relative_X
foreach($row as $cur_rel_x => $check_point)
{
if(to_round($check_point[1]) == to_round($cur_p[1]))
{
$relative_X=$cur_rel_x;
$rule = ($relative_X % 2 == 0 ? 1 : -1);
break 2;
}
//error_check 1
if($cur_rel_x == count($row)-1)
echo "error with calculating relative_X! check your data!\n";
}
}
//error_check 2
if($cur_y == count($sorted_point_rows)-1)
echo "error with calculating pos_y! check your data!\n";
}
}
else
{
$relative_X+=$rule;
$last_point_index+=1;
$cur_p=$sorted_point_rows[$pos_y][$relative_X];
$final_points_poly[$last_point_index]=$cur_p;
$going_Y = !$going_Y;
//search for pos_x:
foreach($sorted_point_columns as $cur_x => $column)
{
if(to_round($column[0][1]) == to_round($cur_p[1]))
{
$pos_x=$cur_x;
//search for relative_Y
foreach($column as $cur_rel_y => $check_point)
{
if(to_round($check_point[0]) == to_round($cur_p[0]))
{
$relative_Y=$cur_rel_y;
$rule = ($relative_Y % 2 == 0 ? 1 : -1);
break 2;
}
//error_check 1
if($cur_rel_y == count($column)-1)
echo "error with calculating relative_Y! check your data!\n";
}
}
//error_check 2
if($cur_x == count($sorted_point_columns)-1)
echo "error with calculating pos_x! check your data!\n";
}
}
if($last_point_index == $points_total-1)
{
$finished=true;
}
}
echo "all points:\n";
print_r($final_points_poly);
/*
//generate markers for google mapping
$out = "var bbs=[];var markers=[];";
$out .= "var pinI = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|ADDE63');";
$out .= "var pinI2 = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FF8C00');";
$out .= "var pinI3 = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|990099');";
$out .= "bbs.push(new google.maps.Polyline({ ";
$out .= "path: [";
foreach($final_points_poly as $m){
$out .= "new google.maps.LatLng(".join(",",$m)."),";
}
$out .= "],";
$out .= "strokeColor: 'black', strokeOpacity: 0.4, strokeWeight: 1 }));";
$f = fopen("bbs.js",'w');
fwrite($f,$out);
fclose($f);
*/
?>

How to echo few lines only from a row named body saved in mysql?

Basically I want to echo only summary of my blog post on a certain page by making a function() that must limit the number of counts of words as specified there.
function sumarize($your_string){
$count++;
$maximum = 10;
foreach(explode("\n", $your_string) as $line){
$count++;
echo $line."\n";
if ($count == $maximum) break;
}
}
Lets say your table (named main) looks like that.
id | blogpost
1 sample1
2 sample2
...
At first you need to connect to db
$db=NEW MYSQLI('localhost', 'username', 'pass', 'dbname') or die ($db->error);
Then write following piece of code
function sumarize($your_string){
$count++;
$maximum = 10;
foreach(explode("\n", $your_string) as $line){
$count++;
echo $line."\n";
if ($count == $maximum) break;
}
}
$result=$db->query("SELECT `id`, `blogpost` FROM `main`");
while($row->fetch_object()){
echo sumarize($row->blogpost);
}
This is how to get work genesis φ's solution
this one takes into account numbers of character whilst ending at the last word without cutting out a character
use
select .... SUBSTR(body,1,300) .....
later you can use this function in php to cut the string at the last space or period so you wont get a half cut word in the end. The second parameter is the number of characters you want.
function shorten_string($string, $characters)
{
$shortened_string = "";
$smaller_string = substr($string, 0, $characters);
$pos_of_last_space = strrpos($smaller_string, " ");
$pos_of_last_break = strrpos($smaller_string, " ");
if (strlen($string) <= $characters) {
$shortened_string = $string;
} elseif (!$pos_of_last_space && !$pos_of_last_break) {
$shortened_string = $smaller_string;
} else {
$break_at = 0;
if ($pos_of_last_space > $pos_of_last_break) {
$break_at = $pos_of_last_space;
} else {
$break_at = $pos_of_last_break;
}
$shortened_string = substr($smaller_string, 0, $break_at);
}
}
NOTE: takes care of spaces put in html with 'nbsp'
Save the summary and body of your blog posts in different columns.

Categories