...

View Full Version : Use PHP function in loop



levani
05-04-2009, 09:23 PM
When I try to use php function in loop I get this warning:


Fatal error: Cannot redeclare function() (previously declared in...
How can I solve this problem???

stfc_boy
05-04-2009, 09:38 PM
Sounds like you are redeclaring the function. Most likely it's being included twice via an include file, this cannot be done. Essentially something like this is probably happening :




function foo()
{
print 'foo';
}

function foo()
{
print 'foo';
}


The second declaration of foo() will provide such an error.

mlseim
05-04-2009, 09:39 PM
We need to see more code ...

venegal
05-04-2009, 09:43 PM
Sounds to me like you are not calling your function in a loop, but rather declaring a function in a loop. Change


while(true) {
function foo(){
echo "bar";
}
}

to


function foo(){
echo "bar";
}
while(true) {
foo();
}

Did I get it right?

levani
05-05-2009, 10:15 AM
Well the code is rather complicated but I'll try to post it...

This is the function which I want to use in loop:


function nicetime($date)
{
if(empty($date)) {
return "No date provided";
}

$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");

$now = time();
$unix_date = strtotime($date);

// check validity of date
if(empty($unix_date)) {
return "Bad date";
}

// is it future date or past date
if($now > $unix_date) {
$difference = $now - $unix_date;
$tense = "ago";

} else {
$difference = $unix_date - $now;
$tense = "from now";
}

for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}

$difference = round($difference);

if($difference != 1) {
$periods[$j].= "";
}

return "$difference $periods[$j] {$tense}";
}

$date = $comment->date;
$result = nicetime($date); // 2 days ago

This is the loop code:


function shenishvnebi($src_count=9999, $src_length=9999, $pre_HTML='', $post_HTML='</li>') {
global $wpdb, $post;

$thePostID = $post->ID;

$divi = '<div style=float:right;">';

$sql = "SELECT DISTINCT ID, date, user_id, post_id, content,
SUBSTRING(content,1,$src_length) AS com_excerpt
FROM wp_shenishvnebi
WHERE post_id = $post->ID ";
$comments = $wpdb->get_results($sql);

$output = $pre_HTML;
$output .= "\n<ul>";
foreach ($comments as $comment) {
$output .= "\n\t<li><small><strong>(" . strip_tags($result) . ") " . $divi . "</strong></small><p> " . strip_tags($comment->com_excerpt) . "</p></div></li>";
}
$output .= "\n</ul>";
$output .= $post_HTML;

echo $output;

}

The $result variable is generated by the function nicetime() but using it in loop causes the error...

Any ideas?

venegal
05-05-2009, 10:37 AM
I don't really get it. You don't even call nicetime() anywhere. Please post the actual code that is causing the error.

levani
05-05-2009, 10:40 AM
I don't really get it. You don't even call nicetime() anywhere. Please post the actual code that is causing the error.

Look at the last line of the first code, the variable $result is equal to nicetime($date) function :)

venegal
05-05-2009, 10:51 AM
Yeah but that's outside the function, so $result is global and you don't get to use it the way you do in shenishvnebi. Furthermore it will always be the same, regardless of where you are in your foreach loop.

Honestly, if you don't tell us how the first snippet is connected to the second one (which one is included where, and how), we'll never know what causes the error, let alone make your code work.

levani
05-05-2009, 11:06 AM
Yeah but that's outside the function, so $result is global and you don't get to use it the way you do in shenishvnebi. Furthermore it will always be the same, regardless of where you are in your foreach loop.

Honestly, if you don't tell us how the first snippet is connected to the second one (which one is included where, and how), we'll never know what causes the error, let alone make your code work.

Well I really don't know which other function may cause this error... I'll post the whole code of the file:


<?php get_header(); ?>

<?php include (TEMPLATEPATH . '/sidebar_single.php'); ?>

<div id="main">

<?php $table_name = 'wp_shenishvnebi'; ?>
<?php

if ($_POST['lev-post-content']) {
date_default_timezone_set('Europe/Moscow');

$insert = "INSERT INTO " . $table_name .
" (date, user_id, post_id, content) " .
"VALUES ('" . date("Y-m-d H:i:s") . "','" . $wpdb->escape($_POST['lev-post-author-id']) . "','" . $wpdb->escape($_POST['lev-post-id']) . "','" . $wpdb->escape($_POST['lev-post-content']) . "')";

$results = $wpdb->query( $insert );
}

?>


<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<div id="mtavari_shekitxva"><div style="float:right; margin-right:5px; margin-bottom:5px; margin-top:10px; font-size:11px; text-align:center;"><?php echo get_avatar( get_the_author_id(), '65' ); ?><br><a href="#" onMouseover="showmenu(event,linkset[1], '180px')" onMouseout="delayhidemenu()" style="color:#000000;"><?php the_author() ?>▼</a>

<div style="margin-top:5px;"></div></div>
<h2><?php the_title(); ?></h2>

<?php the_content('Read the rest of this entry &raquo;'); ?>

<?php
//aris tu ara shenishvna konkretuli kitxvistvis
$checkShenishvna = $wpdb->get_row("SELECT * FROM wp_shenishvnebi WHERE post_id = $post->ID "); ?>

<?php if ($checkShenishvna != NULL ) { ?>
<div id="shenishvnebi">
<?php function punqcia() {
global $post;
$thePostID = $post->ID;
}
?>
<?php
/*
**************************************************************************************************** *
*/

function shenishvnebi($src_count=9999, $src_length=9999, $pre_HTML='', $post_HTML='</li>') {
global $wpdb, $post;

$thePostID = $post->ID;

$divi = '<div style=float:right;">';

$sql = "SELECT DISTINCT ID, date, user_id, post_id, content,
SUBSTRING(content,1,$src_length) AS com_excerpt
FROM wp_shenishvnebi
WHERE post_id = $post->ID ";
$comments = $wpdb->get_results($sql);

$output = $pre_HTML;
$output .= "\n<ul>";
foreach ($comments as $comment) {

function nicetime($date)
{
if(empty($date)) {
return "No date provided";
}

$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");

$now = time();
$unix_date = strtotime($date);

// check validity of date
if(empty($unix_date)) {
return "Bad date";
}

// is it future date or past date
if($now > $unix_date) {
$difference = $now - $unix_date;
$tense = "before";

} else {
$difference = $unix_date - $now;
$tense = "from now";
}

for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}

$difference = round($difference);

if($difference != 1) {
$periods[$j].= "";
}

return "$difference $periods[$j] {$tense}";
}

$date = $comment->date;
$result = nicetime($date); // 2 days ago




$output .= "\n\t<li><small><strong>(" . strip_tags($result) . ") " . $divi . "</strong></small><p> " . strip_tags($comment->com_excerpt) . "</p></div></li>";
}
$output .= "\n</ul>";
$output .= $post_HTML;

echo $output;

}

/*
**************************************************************************************************** *
*/

?> <?php shenishvnebi() ?></div> <?php } ?>
<div style="height:40px"></div></div>

<div id="shekitxvis_dziri">


<?php
global $authordata;
if ( $current_user->ID == $authordata->ID ) { ?>

<div id="shekitxvis_dziri_3">
<div class="dhtmlgoodies_question">Add Info</div>
<div class="dhtmlgoodies_answer">
<div>
<form id="lev-post" name="lev-post" method="post" action=" ">
<input name="lev-post-author-id" type="hidden" value="<?php echo $current_user->ID; ?>" />
<input name="lev-post-id" type="hidden" value="<?php echo $post->ID; ?>" />
<p>
<textarea name="lev-post-content" style="width:330px; height:60px;"></textarea>
</p>
<p>
</p>
<input name="" type="submit" value="Submit" />
</form>
</div>
</div>
</div>

<?php } ?>
<div style="width:1px; float:left; background-color:#000000;"></div>

<?php function function_name() {
global $wp_query;
$thePostID = $wp_query->post->ID;
} ?>


<?php
function get_post_data($postId) {
global $wpdb;
return $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE ID=$postId");
}
?>

<?php
$data = get_post_data($post->ID); ?>

<?php echo $query; ?>

<?php global $current_user;
get_currentuserinfo(); ?>




<?php $upasuxe = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE user_id = $current_user->ID AND comment_post_ID = $post->ID "); ?>



<?php if ($current_user->ID != $data[0]->post_author && $upasuxe->comment_ID == NULL && is_user_logged_in())
echo '<div id="shekitxvis_dziri_upasuxe"><div class="ravi"><center><a href="#respond">უპასუხე</a></center></div></div>';
else
echo '';
?>



</div>
<?php if ($current_user->ID == 1 )
include (TEMPLATEPATH . '/moder.php');
else
echo " ";
?>

<?php trackback_rdf(); ?>

-->

<p class="post-footer align-right">



<?php if (('open' == $post-> comment_status) && ('open' == $post->ping_status) && $upasuxe->comment_ID == NULL ) {

// Both Comments and Pings are open ?>



<?php } elseif (!('open' == $post-> comment_status) && ('open' == $post->ping_status)) {

// Only Pings are Open ?>

<br />Responses are currently closed, but you can <a href="<?php trackback_url(true); ?> " rel="trackback">trackback</a> from your own site.

<?php } elseif (('open' == $post-> comment_status) && !('open' == $post->ping_status)) {

// Comments are open, Pings are not ?>

<br />You can skip to the end and leave a response. Pinging is currently not allowed.

<?php } elseif (!('open' == $post-> comment_status) && !('open' == $post->ping_status)) {

// Neither Comments, nor Pings are open ?>



<?php } ?>



</p>

<?php comments_template(); ?>

<div>

</div>

<?php endwhile; else: ?>

<p>Sorry, no posts matched your criteria.</p>

<?php endif; ?>

</div>

<?php include (TEMPLATEPATH . '/rbar.php'); ?>

<?php get_footer(); ?>

venegal
05-05-2009, 11:12 AM
Right. And now compare your code to my first reply.

Your nicetime function has to be declared outside of any loop (and for that matter, outside of the shenishvnebi function) and only called within the loop.

If you put the function declaration within the loop, it will produce an error on the second iteration, because functions can only be declared once.

levani
05-05-2009, 01:22 PM
OK, I moved the nicetime function from the loop, but now how can I foreach it's value together with my loop?

I tried this but everything got doubled...


<?php
/*
**************************************************************************************************** *
*/



function nicetime($date)
{
if(empty($date)) {
return "No date provided";
}

$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");

$now = time();
$unix_date = strtotime($date);

// check validity of date
if(empty($unix_date)) {
return "Bad date";
}

// is it future date or past date
if($now > $unix_date) {
$difference = $now - $unix_date;
$tense = "ago";

} else {
$difference = $unix_date - $now;
$tense = "from now";
}

for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}

$difference = round($difference);

if($difference != 1) {
$periods[$j].= "";
}

return "$difference $periods[$j] {$tense}";
}



function shenishvnebi($src_count=9999, $src_length=9999, $pre_HTML='', $post_HTML='</li>') {
global $wpdb, $post;

$thePostID = $post->ID;

$divi = '<div style=float:right;">';

$sql = "SELECT DISTINCT ID, date, user_id, post_id, content,
SUBSTRING(content,1,$src_length) AS com_excerpt
FROM wp_shenishvnebi
WHERE post_id = $post->ID ";
$comments = $wpdb->get_results($sql);
$notetime = $wpdb->get_col("SELECT date FROM wp_shenishvnebi WHERE post_id = $post->ID ");
$output = $pre_HTML;
$output .= "\n<ul>";
foreach ($comments as $comment) {
foreach ($notetime as $ravira) {
$date = $ravira;
$result = nicetime($date); // 2 days ago
$output .= "\n\t<li><small><strong>(" . strip_tags($result) . ") " . $divi . "</strong></small><p> " . strip_tags($comment->com_excerpt) . "</p></div></li>";
}
}
$output .= "\n</ul>";
$output .= $post_HTML;

echo $output;

}

/*
**************************************************************************************************** *
*/

?>

venegal
05-05-2009, 01:38 PM
There's no need for the second database query and the second foreach, you already got the date in the first query.

Try


foreach ($comments as $comment) {
$output .= "\n\t<li><small><strong>(" . nicetime($comment->date) . ") " . $divi . "</strong></small><p> " . strip_tags($comment->com_excerpt) . "</p></div></li>";
}


Don't know if that will help the doubling problem though, because I don't know what those queries actually return.

levani
05-05-2009, 01:47 PM
Thaaaaaaaaaaaaaaaaaanks :)))))))

It works at last. I can't believe :D

Thank you so much!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum