Jump to content

myTruncate redeclare() error


pescott

Recommended Posts

Hello all,

 

I am using this bit of code

// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.

function myTruncate($string, $limit, $break=".", $pad="...")
{
  // return with no change if string is shorter than $limit
  if(strlen($string) <= $limit) return $string;

  // is $break present between $limit and the end of the string?
  if(false !== ($breakpoint = strpos($string, $break, $limit))) {
    if($breakpoint < strlen($string) - 1) {
      $string = substr($string, 0, $breakpoint) . $pad;
    }
  }
  
  return $string;
}
$short_omschrijving = myTruncate($omschrijving, 300, " ");

// Begin your table outside of the array
echo("<table id=\"subtable\">
	   <tr> 
		   <td> 
				<table id=\"subtable\"> 
					<tr> 
						<td id=\"subtd\">Adres:</td> 
						<td id=\"enttd\">".$row["straat"]." ".$row["nummer"]."</td> 
					</tr> 
					<tr> 
						<td id=\"subtd\"> </td> 
						<td id=\"enttd\">".$row["postcode"]." ".$row["plaatsnaam"]."</td> 
					</tr> 
					<tr> 
						<td id=\"subtd\">Vraagprijs:</td> 
						<td id=\"enttd\"><b>€ ".$row["vraagprijs"].",00</b></td> 
					</tr> 
					<tr> 
						<td id=\"subtd\">Omschrijving:</td>
						<td id=\"enttd\">".$row["short_omschrijving"]."</td> 
					</tr> 
				</table>
			</td>
		</tr>
		<tr>
			<td> 
				<table id=\"subtable\"> 
					<tr>
						<td colspan=\"2\">Meer weten over dit object? Klikt u dan <a href=javascript:void(window.open('object.php?id=".$row["id"]."','Object','width=550,height=400,top=10,left=10,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes'))>hier</a>.</td>
					</tr> 
				</table>
			</td>
		</tr>");

// Add 1 to the row count

    $row_count++;
}
echo"</table>";

 

to truncate text from a variable in the db called 'omschrijving'.

I receive this error:

Fatal error: Cannot redeclare mytruncate() (previously declared in /home/httpd/vhosts/pescott.nl/subdomains/carelvb/httpdocs/aanbod.php:334) in /home/httpd/vhosts/pescott.nl/subdomains/carelvb/httpdocs/aanbod.php on line 334

where line 334 is this line from the code:

function myTruncate($string, $limit, $break=".", $pad="...")

I checked, there are no duplicates of this line ANYWHERE, so why am I getting a Cannot redeclare error??

 

Hope this makes sense to someone, as it does not make sense to me!  ???

Thanks for the tips people,

 

Chris

Link to comment
Share on other sites

Replace your function with:

if(!function_exists(myTruncate))
{
function myTruncate($string, $limit, $break=".", $pad="...")
{
  // return with no change if string is shorter than $limit
  if(strlen($string) <= $limit) return $string;

  // is $break present between $limit and the end of the string?
  if(false !== ($breakpoint = strpos($string, $break, $limit))) {
    if($breakpoint < strlen($string) - 1) {
      $string = substr($string, 0, $breakpoint) . $pad;
    }
  }
  
  return $string;
}
}

Link to comment
Share on other sites

Papaface, thank you for your reply.

 

This definately took care of the fatal error, yet rendered an empty string. Instead of truncated text, there is now no text at all... so this leaved me woth the issue I first adressed, unfortunately.

 

Any suggestions on how to display the text such that it is truncated after words, instead of midway? For that I used the substr() but that just didn't work well...

Link to comment
Share on other sites

Usually, this error concerning a redeclaration of a function is caused by INCLUDE() or REQUIRE() being called, which when used in that fashion, includes again without any other safety net. You can fix this by using include_once() or require_once() where appropriate. That way, the included scripts will only be parsed if they haven't been included once already.

 

PhREEEk

Link to comment
Share on other sites

PhREEEk,

 

There are two includes, one is for the db connection:

<?php
include_once("db_connect.php");
?>

 

which I changed to include_once(), and the other calls the footer:

 

<?php
include_once("footer.php");
?>

 

Yet, the same error appears. Looking at it, it seems as though the function is declared TWICE in the same line?? ??? ???

Fatal error: Cannot redeclare mynewtruncate() (previously declared in /home/httpd/vhosts/pescott.nl/subdomains/carelvb/httpdocs/aanbod.php:334) in /home/httpd/vhosts/pescott.nl/subdomains/carelvb/httpdocs/aanbod.php on line 334

 

So, I cannot mark the topic SOLVED just yet..

Link to comment
Share on other sites

The code you posted is apparently part of a loop that ends with the following lines (the start of which was not posted) -

 

// Add 1 to the row count

    $row_count++;
}

 

If so, your function definition is inside of a loop. Every pass through the loop, the function definition is redefined (as itself.) Move the function definition to be before the start of the loop.

 

Know thy own code (or at least post all the relevant parts of it so that someone can see what it is doing to be able to help) ::)

Link to comment
Share on other sites

The function WAS before the loop, as the loop was supposed to render a new table row... or so I thought.

 

What I did now was this: (I'll give you the works now!)

<?php
//Select the db structure.
include_once("db_connect.php");

$recordcount=mysql_query("SELECT count(id) FROM objects");
$recordcount=mysql_fetch_row($recordcount);
$recordcount=$recordcount[0];
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
               "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb">
<head>


<script type="text/javascript">
var horizontal_offset="6px" //horizontal offset of hint box from anchor link

/////No further editting needed

var vertical_offset="0" //horizontal offset of hint box from anchor link. No need to change.
var ie=document.all
var ns6=document.getElementById&&!document.all

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=(whichedge=="rightedge")? parseInt(horizontal_offset)*-1 : parseInt(vertical_offset)*-1
if (whichedge=="rightedge"){
var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-30 : window.pageXOffset+window.innerWidth-40
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure+obj.offsetWidth+parseInt(horizontal_offset)
}
else{
var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetHeight
}
return edgeoffset
}

function showhint(menucontents, obj, e, tipwidth){
if ((ie||ns6) && document.getElementById("hintbox")){
dropmenuobj=document.getElementById("hintbox")
dropmenuobj.innerHTML=menucontents
dropmenuobj.style.left=dropmenuobj.style.top=-500
if (tipwidth!=""){
dropmenuobj.widthobj=dropmenuobj.style
dropmenuobj.widthobj.width=tipwidth
}
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+obj.offsetWidth+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px"
dropmenuobj.style.visibility="visible"
obj.onmouseout=hidetip
}
}

function hidetip(e){
dropmenuobj.style.visibility="hidden"
dropmenuobj.style.left="-500px"
}

function createhintbox(){
var divblock=document.createElement("div")
divblock.setAttribute("id", "hintbox")
document.body.appendChild(divblock)
}

if (window.addEventListener)
window.addEventListener("load", createhintbox, false)
else if (window.attachEvent)
window.attachEvent("onload", createhintbox)
else if (document.getElementById)
window.onload=createhintbox

</script>


<title>H U I Z E N - B U S I N E S S - Doe eens gek en koop een pand...</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="imagetoolbar" content="false" />
<meta name="keywords" content="Makelaardij en andere keywords... NOG IN TE VULLEN">
<meta name="author" content="Chris P. Pescott">
<meta name="robots" content="follow">
<style type="text/css">
<!--
@import url("c/cvb01.css");
-->
</style>
<!--[if IE]>
<style type="text/css">
p.note-general, p.note-warning { color: #666666; }
</style>
<![endif]-->
<!--[if IE 7]>
<style type="text/css">
#footer { clear: both; background: url(../i/cvb01_footer.jpg) no-repeat 50% 100%;
    padding-top: 0px;
    padding-right: 0px;
    padding-bottom: 81px;
    padding-left: 0px;
}
</style>
<![endif]-->
<!--[if IE 6]>
<style type="text/css">
#footer { height: 1em; }
</style>
<![endif]-->
<!--[if IE 5.5]>
<style type="text/css">
pre { width: 453px; }
</style>
<![endif]-->
</head>
<body id="bescherm" class="homepage">
<div id="wrapper-a">
<div id="wrapper-b">
<div id="heading">
<p id="heading-intro">
</p>
<ul id="nav-a">
<li id="nav-a-start"><a href="index.php">start</a></li>
<li id="nav-a-taxaties"><a href="taxaties.php">taxaties</a></li>
<li id="nav-a-aanbod"><a href="aanbod.php">aanbod</a></li>
<li id="nav-a-hypotheek"><a href="index.php">hypotheek</a></li>
<li id="nav-a-contact"><a href="contact.php">contact</a></li>
</ul>
</div>
<div id="content">
<div id="content-a">
<div id="content-a-inner">
<table id="maintable">
<tr>

<td>
  <!-- InstanceBeginEditable name="main content" -->

<h3 id="aanbod">Het gehele actueel aanbod:</h3>
<br />

<?php
//Select the db structure.
include_once("db_connect.php");

// how many rows to show per page
$rowsPerPage = 15;

// by default we show first page
$pageNum = 1;

// if $_GET['page'] defined, use it as page number
if(isset($_GET['page'])) {
    $pageNum = $_GET['page'];
}

// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;
$id=1;
if (isset($_GET['id']))
   $id = $_GET['id'];
?>

<table id="subtable">
<form name="data_search" id="search" method="GET" action="">
<tr>
    	<td colspan="2" align="right">Vul een zoekterm in: <input type="text" size="27" name="textSearch" /> binnen de categorie:</td>
	<td width="20"> </td>
	<td><select name="selectSearch">
		<option value="plaatsnaam">- selecteer een optie -     </option>
		<option value="straat">Straat</option>
		<option value="wijk">Wijk</option>
		<option value="plaatsnaam">Plaatsnaam</option>
		<option value="type_woning">Type woning</option>
		<option value="vraagprijs">Vraagprijs</option>
		<option value="label">Energielabel</option>
    		</select>
	</td>
    </tr>
<tr>
	<td width="40%"> </td>
    	<td align="right">Hoe wilt u zoeken?</td>
	<td width="20"> </td>
    	<td><select name="matchCase">
		<option value="similar">- selecteer een optie -     </option>
		<option value="exact">Exacte zoekterm      </option>
		<option value="similar">Bevat de zoekterm</option>
		</select>
	</td>
</tr>
<tr>
    	<td colspan="2" align="right">Hoe wilt u de resultaten weergegeven hebben?</td>
	<td width="20"> </td>
    	<td><select name="sortOrder">
		<option value="asc">- selecteer een optie -     </option>
		<option value="asc">oplopend</option>
		<option value="desc">aflopend</option>
		</select>
	</td>
  </tr>
  <tr>
	<td colspan="2" align="right" height="44" valign="bottom"><input type="submit" name="submitSearch" value="Zoekopdracht ingevuld? Zoek nu!" /></td>
	<td width="20"> </td>
	<td height="44" valign="bottom"><input type="submit" name="submitViewAll" value="Alle resultaten" /></td>
</tr>
<tr>
	<td colspan="4" align="center" height="44" valign="bottom">Of klik direct op de eerste letter van de <b>stad waarin u zoekt</b> om de resultaten te bekijken:</td>
</tr>
<tr>
    	<td colspan="4" align="center"><?php
                echo "| ";
                for ($i=65; $i<=90; $i++)
                     echo "<a href=?char=".chr($i+32).">".chr($i). "</a> | ";
                                        ?></td>
</tr>
<tr>
	<td colspan="4"><hr></td>
    </tr>
</form>
</table>

<?php
// how many rows do we have in the database

// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.

function mytruncate($string, $limit, $break=".", $pad="...")
{
  // return with no change if string is shorter than $limit
  if(strlen($string) <= $limit) return $string;

  // is $break present between $limit and the end of the string?
  if(false !== ($breakpoint = strpos($string, $break, $limit))) {
    if($breakpoint < strlen($string) - 1) {
      $string = substr($string, 0, $breakpoint) . $pad;
    }
  }
  
  return $string;
}

if (isset($_GET['submitSearch']))
{
        $textSearch = $_GET['textSearch'];
        $selectSearch = $_GET['selectSearch'];
        $matchCase = $_GET['matchCase'];
        $sortOrder = $_GET['sortOrder'];

        if ($matchCase=="exact")
		{
                $query = "SELECT * from objects
                          WHERE $selectSearch = '$textSearch'
                          ORDER BY plaatsnaam $sortOrder
                          LIMIT $offset, $rowsPerPage";
		}
        else
		{
                $query = "SELECT * from objects
                          WHERE $selectSearch like '%$textSearch%'
                          ORDER BY plaatsnaam $sortOrder
                          LIMIT $offset, $rowsPerPage";
		}
}
        elseif (isset($_GET['char']))
		{
                 $char = $_GET['char'];
                 $query = "SELECT * FROM objects WHERE plaatsnaam like '$char%' ORDER BY plaatsnaam ASC LIMIT $offset, $rowsPerPage";
		}
        else
		{
              $query = "SELECT * FROM objects ORDER BY plaatsnaam ASC LIMIT $offset, $rowsPerPage";
		}

// Retrieve all the data from the "objects" table
$result = mysql_query($query) or die(mysql_error());
$recordcount = mysql_num_rows($result);
if ($recordcount==0)
    echo "Helaas, er zijn <strong>GEEN</strong> resultaten die aan geze zoekopdracht voldoen.";
if ($recordcount==1)
    echo "Er is <strong>$recordcount</strong> resultaat:";
if ($recordcount > 1)
    echo "Er zijn <strong>$recordcount</strong> resultaten:";
    
// Define your colors for the alternating rows
$color1 = "#eeeeee";
$color2 = "#dcdcdc";
$row_count = 0;

// We are going to use the "$row" method for this query. This is just my preference.

// Haal de resultaten uit de database
while($row = mysql_fetch_array($result)) {
    $id = $row["id"];
    $plaatsnaam = $row["plaatsnaam"];
    $soort_object = $row["soort_object"];
    $type_woning = $row["type_woning"];
    $straat = $row["straat"];
    $nummer = $row["nummer"];
    $postcode = $row["postcode"];
    $wijk = $row["wijk"];
    $vraagprijs = $row["vraagprijs"];
    $oppervlakte = $row["oppervlakte"];
    $perceel = $row["perceel"];
    $inhoud = $row["inhoud"];
    $kamers = $row["kamers"];
    $bouwjaar = $row["bouwjaar"];
    $kenmerken = $row["kenmerken"];
    $balkon = $row["balkon"];
    $tuin = $row["tuin"];
    $garage = $row["garage"];
    $berging = $row["berging"];
    $verwarming = $row["verwarming"];
    $cv = $row["cv"];
    $soort_cv = $row["soort_cv"];
    $bouwjaar_cv = $row["bouwjaar_cv"];
    $isolatie = $row["isolatie"];
    $label = $row["label"];
    $oplevering = $row["oplevering"];
$beschikbaar = $row["beschikbaar"];
$short_omschrijving = $row["short_omschrijving"];
$short_omschrijving = mytruncate($omschrijving, 300, " ");

// Now we do this small line which is basically going to tell
// PHP to alternate the colors between the two colors we defined above.

$row_color = ($row_count % 2) ? $color1 : $color2;

// Echo your table row and table data that you want to be looped over and over here.

// Begin your table outside of the array
echo("<table id=\"subtable\">
	   <tr> 
		   <td> 
				<table id=\"subtable\"> 
					<tr> 
						<td id=\"subtd\">Adres:</td> 
						<td id=\"enttd\">".$row["straat"]." ".$row["nummer"]."</td> 
					</tr> 
					<tr> 
						<td id=\"subtd\"> </td> 
						<td id=\"enttd\">".$row["postcode"]." ".$row["plaatsnaam"]."</td> 
					</tr> 
					<tr> 
						<td id=\"subtd\">Vraagprijs:</td> 
						<td id=\"enttd\"><b>€ ".$row["vraagprijs"].",00</b></td> 
					</tr> 
					<tr> 
						<td id=\"subtd\">Omschrijving:</td>
						<td id=\"enttd\">".$row["short_omschrijving"]."</td> 
					</tr> 
				</table>
			</td>
		</tr>
		<tr>
			<td> 
				<table id=\"subtable\"> 
					<tr>
						<td colspan=\"2\">Meer weten over dit object? Klikt u dan <a href=javascript:void(window.open('object.php?id=".$row["id"]."','Object','width=550,height=400,top=10,left=10,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes'))>hier</a>.</td>
					</tr> 
				</table>
			</td>
		</tr>");

// Add 1 to the row count

    $row_count++;
}
echo"</table>";

// how many rows we have in database
$query = "SELECT COUNT(id) AS numrows FROM objects";
$result = mysql_query($query) or die('Er is een fout opgetreden bij het zoeken in de database');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];

// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);

// print the link to access each page
$self = $_SERVER['PHP_SELF'];
$nav = '';
for($page = 1; $page <= $maxPage; $page++)
{
        if ($page == $pageNum) {
                $nav .= " $page "; // no need to create a link to current page
}
        else
		{
                $nav .= " <a href=\"$self?page=$page\">$page</a> ";
		}
}
        if ($pageNum > 1) {
                $page = $pageNum - 1;
                $prev = " <a href=\"$self?page=$page\">vorige</a> ";

                $first = " <a href=\"$self?page=1\">eerste</a> ";
		}
        else
		{
                $prev = ' '; // we're on page one, don't print previous link
                $first = ' '; // nor the first page link
		}

        if ($pageNum < $maxPage) {
                $page = $pageNum + 1;
                $next = " <a href=\"$self?page=$page\">volgende</a> ";

                $last = " <a href=\"$self?page=$maxPage\">laatste</a> ";
		}
        else
		{
                $next = ' '; // we're on the last page, don't print next link
                $last = ' '; // nor the last page link
		}
?>

<center>

<?php
echo $first . $prev . $nav . $next . $last;
?>

</center>
  <!-- InstanceEndEditable -->

</td>
</tr>
</table>
</div>
</div>

<?php
include_once("footer.php");
?>

</div>
</div>
</div>
</body>
</html>

 

Yet, the returned data from the table is empty. So, I must still be doing something horribly wrong...

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.